我正在尝试将Typescript 2.0的区分联合类型与RxJS一起使用,但是我收到的错误是我返回的对象不是union类型的类型之一 .
这是我的类型:
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"};
}
当我试着像这样返回一个_2400279时:
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
应该是有 Value 的 "circle"
而不是类型 string
是必要的吗?
1 回答
通过像
Observable.of({ kind: "center" })
这样的调用,TypeScript无法从匿名参数中推断出类型 .您可以通过在调用泛型
of
方法时将type variable指定为Shape
来解决您的问题:指定类型变量后,TypeScript不再需要推断类型 .