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;
私はちょうどShape
がObservable
を使用していない返すこの機能は完全に罰金コンパイル:
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"
であることを理解するために、これを完全に間違っているか、必要なキャストですか?
これは、Observable.ofが静的関数であるためですか?例えば 'subject:Subject: 'だったら、' subject.next(t) 'を呼び出すときに' typeof t === T'を理解できるはずですか? –
lambdabutz
'Subject'をお持ちの場合、 'next'はあなたの質問に記載されているエラーに影響しません。 –
cartant