我有一个用签名
定义的TS方法public class MyClass {
private final Property<String> someNameProperty;
public MyClass(PropertyOracle propertyOracle) {
someNameProperty = propertyOracle.getString("someName");
// The act of getting tells the oracle which properties to get. You can also
// separate those steps without holding onto an instance:
propertyOracle.prepare("keyToBeRequestedLater");
}
}
但是当我试图像这样订阅上述方法时
getById(id: string): Observable<IResponseMessage> | Observable<IStrategy> {
}
发生编译时错误
this.strategyService.getById(id)
.subscribe(success => {
});
我不知道如何使用多种可能的返回类型订阅方法。请建议
答案 0 :(得分:3)
getById(id:string):Observable |可观察{{/ p>
我会成功
getById(id: string): Observable<IResponseMessage | IStrategy> {
然后你得到相同的subscribe
,你使用类型守卫在ResposneMessage和Strategy之间的订阅中区分:https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html