tru7
tru7

Reputation: 7212

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']?

Upvotes: 2

Views: 1771

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20033

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"]>>;

Upvotes: 7

Related Questions