首页 > 解决方案 > 如何实现 PromiseLike 接口?

问题描述

我尝试使用 thenable 支持实现自动提交过程。但我无法绕过上次抱怨的类型错误:

type JobResolve = () => void

export class Job implements PromiseLike<JobResolve> {
  public then<TResult1 = JobResolve>(onfulfilled?: ((value: JobResolve) => (PromiseLike<TResult1> | TResult1)) | undefined | null): PromiseLike<TResult1> {
    const done = () => {}
    if (typeof onfulfilled === 'function') {
      const thenable = Promise.resolve(onfulfilled(done))
      done()
      return thenable
    } else {
      // Error here!
      // TS2322: '() => void' is assignable to the constraint of type 'TResult1', but 'TResult1' could be instantiated with a different subtype of constraint '{}'.
      return Promise.resolve(done)
    }
  }
}

如何解决?(没有Promise.resolve(done as any)

标签: typescript

解决方案


您的else分支在PromiseLike. 考虑这个例子

async function f() {
    let t: {a: string} = await Promise.resolve(1).then<{a: string}>();
    console.log(t, t.a, typeof t, typeof t.a);
}
f();

tnumbernot类型object,但类型系统认为它是一个对象。

如果您的目标是提供与 的合规性Promise,那么您不妨将返回值转换为返回类型,如下所示:

    return Promise.resolve(done) as PromiseLike<TResult1>

或者,为了更安全,抛出异常。


推荐阅读