方法一
通过 Promise 的构造函数,声明返回值的泛型类型。
1 2 3 4 5 |
type resolveType = { width: number; height: number } return new Promise<resolveType>(resolve => { resolve({ width: 100, height: 200 }) }) |
方法二
修改 reslove
的类型定义
1 2 3 |
return new Promise((resolve: (value: { width: number; height: number }) => void) => { resolve({ width: 100, height: 200 }) }) |
原理:
1 2 3 4 5 6 7 |
/** * 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
值得类型。
参考文章:
Keep Your Promises in TypeScript using async/await