【发布时间】:2022-10-16 23:38:16
【问题描述】:
为什么 Typescript 报错如下代码,如何正确输入onfulfilled 回调?
const thenableObj = {
then(onfulfilled: (val: string) => void) {
onfulfilled("done")
}
}
Promise.resolve(thenableObj); // error here
此外,TS 定义了一个PromiseLike 接口,我认为这不过是一种定义 thenable 对象的方法(如果有错误请纠正我)。
interface PromiseLike<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(
onfulfilled?:
| ((value: T) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?:
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
| undefined
| null
): PromiseLike<TResult1 | TResult2>;
}
我认为问题在于PromiseLike 定义then 以返回PromiseLike<TResult1 | TResult2>,但我的then 返回void。
【问题讨论】:
标签: typescript