tru*_*ru7 2 asynchronous return-type typescript
令人惊讶的是,Typescript 可以给出函数或类方法的返回类型,ReturnType<>如下所示:
class Foo{
bar(){ return {one:1, two:2};}
}
type typeBar = ReturnType<Foo['bar']>;
Run Code Online (Sandbox Code Playgroud)
但是,如果该方法是异步的,是否可以获得已解决的 Promise 的类型?
class Foo{
async asyncBar() { return new Promise((resolve) => resolve({ one: 1, two: 2 }));}
}
type typeBar = ReturnType<Foo['asyncBar']>; // the type here is Promise
Run Code Online (Sandbox Code Playgroud)
那么要从什么运营商那里得到{one:number, two:number}呢Foo['asyncBar']?
您可以定义一个类型,例如
type Unpack<T> = T extends Promise<infer U> ? U : T;
Run Code Online (Sandbox Code Playgroud)
然后使用
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"]>>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1725 次 |
| 最近记录: |