如何在Typescript中定义Promise的返回值类型

问题

如何在 Typescript 中定义 Promise 的返回值类型?

描述

如图所示,可以看到 Promise 中,reslove() 方法传入的是 number 类型。但是,Typescript 感知到的类型却是 Promise<{}>。如何让

Promise 无法感知reslove 的类型

解决办法

方法一

通过 Promise 的构造函数,声明返回值的泛型类型。

通过Promise的构造函数声明返回类型

方法二

修改 reslove的类型定义

重新定义reslove函数的类型

原理

    /**
     * Creates a new Promise.
     * @param executor A callback used to initialize the promise. This callback is passed two arguments:
     * a resolve callback used resolve the promise with a value or the result of another promise,
     * and a reject callback used to reject the promise with a provided reason or error.
     */
    new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise;

Promise的类型定义如上,我们可以看到 Promise 返回值的类型定义,可以由两部分决定。第一个是构造时的泛型值,第二个是 reslove函数 value值得类型。

参考文章

  • Keep Your Promises in TypeScript using async/await

你可能感兴趣的:(如何在Typescript中定义Promise的返回值类型)