令人惊奇的是,Typescript可以使用ReturnType<>
给出函数或类方法的返回类型,如下所示:
class Foo{
bar(){ return {one:1, two:2};}
}
type typeBar = ReturnType<Foo['bar']>;
但是,如果该方法是异步的,是否有可能获得已解决的Promise的类型?
class Foo{
async asyncBar() { return new Promise((resolve) => resolve({ one: 1, two: 2 }));}
}
type typeBar = ReturnType<Foo['asyncBar']>; // the type here is Promise
那么从{one:number, two:number}
获得Foo['asyncBar']
的运营商将是什么?
答案 0 :(得分:3)
您可以定义类似
的类型type Unpack<T> = T extends Promise<infer U> ? U : T;
然后使用
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"]>>;