TypeScript async type guard using Promise

Viewed 2619

I'm trying to define an asynchronous type guard. I can do the following synchronously:

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);

But I'm not sure how to do the same async. This is what I tried:

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);
});

Try it here

Any help would be appreciated!

1 Answers
Related