【问题标题】:How to correctly type the onfulfilled callback of a thenable object?如何正确键入 thenable 对象的 onfulfilled 回调?
【发布时间】:2022-10-16 23:38:16
【问题描述】:

为什么 Typescript 报错如下代码,如何正确输入onfulfilled 回调?

const thenableObj = {
    then(onfulfilled: (val: string) => void) {
        onfulfilled("done")
    }
}

Promise.resolve(thenableObj); // error here

链接到TS Playground

此外,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&lt;TResult1 | TResult2&gt;,但我的then 返回void

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题是 onfulfilled 回调没有返回任何东西,所以 Promise.resolve 方法不知道如何处理它。您需要从 onfulfilled 回调中返回一个值,或者从 onfulfilled 回调中返回一个 Promise。

    const thenableObj = {
        then(onfulfilled: (val: string) => void) {
            onfulfilled("done")
        }
    }
    
    Promise.resolve(thenableObj);
    "
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 2021-01-29
      • 2023-03-23
      • 2012-04-18
      • 2023-02-02
      • 2020-11-19
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多