2017-03-08 9 views
3

次のカスタムRxJS演算子(実際にはデモ用の.filter相当のもの)は現在、4.0.0-rc.2のAngular 4.0コンポーネントで宣言されています。TypescriptでカスタムRxJS演算子のシグニチャを指定する

declare module 'rxjs/Observable' { 
    interface Observable<T> { 
    restrictToCommand<U>(f: (x: T) => U): Observable<U>; 
    } 
} 

Observable.prototype.restrictToCommand = function (cmd) { 
    return new Observable((observer) => { 
    const obs = { 
     next: (x) => { 
     if (x.command === cmd || cmd.indexOf(x.command) !== -1) { 
      observer.next(x); 
     } 
     }, 
     error: (err) => observer.error(err), 
     complete:() => observer.complete() 
    }; 
    return this.subscribe(obs); 
    }); 
}; 

関数シグネチャは、現在暗黙anyタイプとしてcmd受け付けます。私はこのような許可の種類を制限しようとしています:

restrictToCommand<U>(f: (x: T | T[]) => U): Observable<U>; 

Observable.prototype.restrictToCommand = function (cmd: string | string[]) { ... } 

を、これは次のコンパイラエラーの原因として、私は、供給型定義を上書きすることができないようにしかし、それはそう:

ERROR in (...)/mycomponent.component.ts (11,1): Type '(cmd: string | string[]) => Observable<{}>' is not assignable to type '<U>(f: (x: any) => U) => Observable<U>'. 
    Types of parameters 'cmd' and 'f' are incompatible. 
    Type '(x: any) => any' is not assignable to type 'string | string[]'. 
     Type '(x: any) => any' is not assignable to type 'string[]'. 
     Property 'push' is missing in type '(x: any) => any'.) 

私には何が欠けていますか?

答えて

6

私はカスタムRxJS演算子を定義するとき、私は通常それをこのような何か:私は宣言マージでtypeofを使用すると、物事を簡素化することを見つける

import { Observable } from 'rxjs/Observable'; 

function restrictToCommand<T>(
    this: Observable<T>, 
    cmd: string | string[] 
): Observable<T> { 

    return new Observable((observer) => { 
    const obs = { 
     next: (x) => { 
     if (x.command === cmd || cmd.indexOf(x.command) !== -1) { 
      observer.next(x); 
     } 
     }, 
     error: (err) => observer.error(err), 
     complete:() => observer.complete() 
    }; 
    return this.subscribe(obs); 
    }); 
} 

Observable.prototype.restrictToCommand = restrictToCommand; 

declare module 'rxjs/Observable' { 
    interface Observable<T> { 
    restrictToCommand: typeof restrictToCommand; 
    } 
} 

を。

+0

これは非常にきれいなアプローチです、ありがとうございます! –

関連する問題