我的课堂上有这个抽象变量:
abstract save(): Promise<boolean> | Observable<boolean>;
我有一个函数可以运行派生类实现的save
函数。我如何检查它是一个应许还是可观察的?
executeSave(): void {
if (///// is this a promise??? /////) {
(<Promise<boolean>>this.save()).then(isSaved => { ... });
} else {
(<Observable<boolean>>this.save()).subscribe(isSaved => { ... });
}
}
答案 0 :(得分:3)
最简单的方法是使用rxjs内置的isObservable测试:
import { isObservable } from "rxjs";
executeSave(): void {
const toSave = this.save();
if (isObservable(toSave)) { // checks if observable
toSave.subscribe(isSaved => { ... });
} else { // only 2 options so this is a promise
toSave.then(isSaved => { ... });
}
}
也不再需要强制输入
答案 1 :(得分:2)
可以使用方便的instanceof
运算符来实现。这也给您带来的好处是,变量的类型(在您的情况下为toSave
)将被自动推断为if块内instanceof
操作右侧的类型。这样您就无需打字。
import { Observable } from "rxjs";
executeSave(): void {
const toSave = this.save();
if (toSave instanceof Observable) {
// Since you used "instanceof" here, typescript knows that "toSave" is of type "Observable" inside this if
toSave.subscribe(isSaved => { /* omitted */ });
} else if (toSave instanceof Promise) { // else would be enough, since there are only two possible types for "toSave"
// Same goes for the Promise
toSave.then(isSaved => { /* omitted */ });
}
}
编辑:如评论所述,不需要第二次类型检查。我相应地调整了代码中的注释。