2017-01-03 6 views
3

Typescript 2.0の識別されたユニオンタイプをRxJSで使用しようとしていますが、返すオブジェクトがRxJSのタイプではないというエラーが発生しています。ユニオンタイプ。ここでTypescriptはObservable.ofでユニオンタイプを区別しました

は私のタイプです:

interface Square { 
    kind: "square"; 
    width: number; 
} 

interface Circle { 
    kind: "circle"; 
    radius: number; 
} 

interface Center { 
    kind: "center"; 
} 

type Shape = Square | Circle | Center; 

私はちょうどShapeObservableを使用していない返すこの機能は完全に罰金コンパイル:

function shapeFactory(width: number): Shape { 
    if (width > 5) { 
    return {kind: "circle", radius: width}; 
    } else if (width < 2) { 
    return {kind: "square", width: 3}; 
    } 

    return {kind: "center"}; 
} 

私が代わりにそうようObservable<Shape>を返すようにしようとすると:

function shapeFactoryAsync(width: number): Observable<Shape> { 
    if (width > 5) { 
    return Observable.of({kind: "circle", radius: width}); 
    } else { 
    return Observable.of({kind: "center"}); 
    } 
} 

私はコンパイルエラー番目:

Type 'Observable<{ kind: string; radius: number; }>' is not assignable to type 'Observable<Shape>'. 
    Type '{ kind: string; radius: number; }' is not assignable to type 'Shape'. 
    Type '{ kind: string; radius: number; }' is not assignable to type 'Center'. 
     Types of property 'kind' are incompatible. 
     Type 'string' is not assignable to type '"center"'. 

私はkindはすべてShapeタイプにわたって差別であるので、私の最初の戻り値は、タイプObservable<{ kind: "circle"; radius: number; }>であろうことを期待しています。奇妙なことに、Observable.of({kind: "center"})で他のデータが関連付けられていない可能性があります。

私は明示的にオブジェクトを代入し、そうのような割り当てにタイプを与えればそれを修正することができています:それは、不要なキャストする必要がありますように、これはそうですけど

let circle: Circle = {kind: "circle", radius: width}; 
return Observable.of(circle); 

の代わりにが値"circle"であることを理解するために、これを完全に間違っているか、必要なキャストですか?

答えて

2

Observable.of({ kind: "center" })のような呼び出しでは、TypeScriptは匿名の引数から型を推論することができません。

あなたはジェネリックofメソッドを呼び出すときにShapeとしてtype variableを指定することで、あなたの問題を解決することができます:指定された型の変数に

function shapeFactoryAsync(width: number): Observable<Shape> { 
    if (width > 5) { 
    return Observable.of<Shape>({ kind: "circle", radius: width }); 
    } else { 
    return Observable.of<Shape>({ kind: "center" }); 
    } 
} 

を、活字体は、もはやタイプを推測することがありません。

+0

これは、Observable.ofが静的関数であるためですか?例えば ​​'subject:Subject: 'だったら、' subject.next(t) 'を呼び出すときに' typeof t === T'を理解できるはずですか? – lambdabutz

+0

'Subject 'をお持ちの場合、 'next'はあなたの質問に記載されているエラーに影響しません。 – cartant

関連する問題