问题
如何在 Typescript 中定义 Promise 的返回值类型?
描述
如图所示,可以看到 Promise 中,reslove()
方法传入的是 number 类型。但是,Typescript 感知到的类型却是 Promise<{}>
。如何让
解决办法
方法一
通过 Promise 的构造函数,声明返回值的泛型类型。
方法二
修改 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 <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
Promise
的类型定义如上,我们可以看到 Promise 返回值的类型定义,可以由两部分决定。第一个是构造时的泛型值,第二个是 reslove
函数 value
值得类型。