Reputation: 7212
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
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