【发布时间】:2018-01-01 20:53:28
【问题描述】:
我正在尝试定义一个异步类型保护。我可以同步执行以下操作:
class Foo {
public type = 'Foo';
}
// Sync type guard:
function isFoo(obj: any): obj is Foo {
return typeof obj.type !== 'undefined' && obj.type === 'Foo';
}
function useFoo(foo: Foo): void {
alert(`It's a Foo!`);
}
const a: object = new Foo();
if (isFoo(a)) useFoo(a);
但我不确定如何执行相同的异步操作。这是我尝试过的:
class Bar {
public getType = () => new Promise(resolve => {
setTimeout(() => resolve('Bar'), 1000);
});
}
// Async type guard:
async function isBar(obj: any): Promise<obj is Bar> {
if (typeof obj.getType === 'undefined') return false;
const result = await obj.getType();
return result === 'Bar';
}
function useBar(bar: Bar): void {
alert(`It's a Bar!`);
}
const b: object = new Bar();
isBar(b).then(bIsBar => {
if (bIsBar) useBar(b);
});
任何帮助将不胜感激!
【问题讨论】:
-
它似乎还不是一个功能。也许你可以submit the idea?
-
当使用 tsc 2.0.9 和节点 7.7.3 定位 es6 时,这似乎工作正常。
标签: typescript asynchronous types