gpt4 book ai didi

typescript - 异步方法的返回类型

转载 作者:行者123 更新时间:2023-12-02 17:01:14 25 4
gpt4 key购买 nike

令人惊奇的是,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']

最佳答案

你可以定义一个类型

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

关于typescript - 异步方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54110490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com