Ich versuche, einen asynchronen Wächter zu definieren. Ich kann das folgende synchron tun:TypeScript async Typ Wache mit Promise
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);
Aber ich bin nicht sicher, wie man das gleiche async tut. Das ist, was ich versucht:
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);
});
Jede mögliche Hilfe würde geschätzt!
Es scheint, es ist noch keine Funktion. Vielleicht könntest du [die Idee einreichen] (https://github.com/Microsoft/TypeScript/issues)? – Paleo
Dies scheint gut zu funktionieren, wenn man es6 mit tsc 2.0.9 und Knoten 7.7.3 anvisiert. –