我试图在RxJS中使用TypeScript2.0的区分的联合类型,但是我得到一个错误,我返回的对象不是联合类型的类型之一。
以下是我的类型:
interface Square {
kind: "square";
width: number;
}
interface Circle {
kind: "circle";
radius: number;
}
interface Center {
kind: "center";
}
type Shape = Square | Circle | Center;在这个函数中,我只返回一个没有使用Observable的Shape,编译完全正常:
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"'.我希望我的第一个返回值是Observable<{ kind: "circle"; radius: number; }>类型,因为kind是所有Shape类型的区别。奇怪的是,它可以使用Observable.of({kind: "center"}),可能是因为没有其他数据与之关联?
如果我显式地给对象赋值,并为赋值赋予如下类型,我就能够修复它:
let circle: Circle = {kind: "circle", radius: width};
return Observable.of(circle);虽然这看起来应该是一个不必要的演员阵容。
我这样做是完全错误的,还是为了找出kind应该是值"circle"而不是类型string而进行强制转换是必要的
https://stackoverflow.com/questions/41454009
复制相似问题