問題
如何在 Typescript 中定義 Promise 的返回值類型?
描述
如圖所示,可以看到 Promise 中,reslove() 方法傳入的是 number 類型。但是,Typescript 感知到的類型卻是 Promise<{}>。如何讓

Promise 無法感知reslove 的類型
解決辦法
方法一
通過 Promise 的構(gòu)造函數(shù),聲明返回值的泛型類型。

通過Promise的構(gòu)造函數(shù)聲明返回類型
方法二
修改 reslove的類型定義

重新定義reslove函數(shù)的類型
原理
/**
* 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 返回值的類型定義,可以由兩部分決定。第一個(gè)是構(gòu)造時(shí)的泛型值,第二個(gè)是 reslove函數(shù) value值得類型。