Search code examples
typescriptasynchronousreturn-type

Return type of async method


Amazingly Typescript can give the return type of a function or a class method with ReturnType<> as in:

class Foo{
    bar(){ return {one:1, two:2};}
}

type  typeBar = ReturnType<Foo['bar']>;

However, if the method is async, is it possible to get the type of the resolved promise?

class Foo{
    async asyncBar() { return new Promise((resolve) => resolve({ one: 1, two: 2 }));}
}
type  typeBar = ReturnType<Foo['asyncBar']>; // the type here is Promise

So what would be the operator(s) to get {one:number, two:number} from Foo['asyncBar']?


Solution

  • You can define a type like

    type Unpack<T> = T extends Promise<infer U> ? U : T;
    

    and then use

    class Foo {
        async asyncBar() { return new Promise<{one:1, two:2}>((resolve) => resolve({ one: 1, two: 2 }));}
    }
    
    type Unpack<T> = T extends Promise<infer U> ? U : T;
    type typeBar = Unpack<ReturnType<Foo["asyncBar"]>>;