首页 > 解决方案 > 打字稿中的多态承诺

问题描述

我正在尝试在返回 Promise 的 Typescript 类中参数化一个函数。完成承诺后,我将返回this,调用者以多态方式使用它。我收到一个我不太明白的编译时错误。

这个(平凡的)代码编译得很好:

class foo {
  aFoo(): Promise<foo> {
    return new Promise<foo>(resolve => resolve(this));
  }
}
class bar extends foo {
  test() {
    this.aFoo().then(result => {
      let val: bar;
      val = result as bar;
    });
  }
}

但是,我宁愿不必降低结果,即。val = result as bar每次我调用这个,所以我试图参数化超类中的函数:

class foo {
  aFoo<T extends foo>(): Promise<T> {
    return new Promise<T>(resolve => resolve(this));
  }
}
class bar extends foo {
  test() {
    this.aFoo<bar>().then(result => {
      let val: bar;
      val = result;
    });
  }
}

我在resolve(this)aFoo 返回的承诺中遇到编译器错误。

错误说:

this: this
Argument of type 'this' is not assignable to parameter of type 'T | PromiseLike<T> | undefined'.
  Type 'foo' is not assignable to type 'T | PromiseLike<T> | undefined'.
    Type 'foo' is not assignable to type 'PromiseLike<T>'.
      Type 'this' is not assignable to type 'PromiseLike<T>'.
        Property 'then' is missing in type 'foo' but required in type 'PromiseLike<T>'.ts(2345)
lib.es5.d.ts(1393, 5): 'then' is declared here.

我可以通过做一些无关的转换来抑制编译器错误:

return new Promise<foo>(resolve => resolve((this as unknown) as T));

我可以使用解决方法,但我想了解编译器反对什么。我认为这可能与 JS/TS 中 this 的怪异有关,但是将其更改为箭头函数并不能消除错误。这个错误也让我感到奇怪,因为它将 this 描述为一种类型,而不是一个实例——但我确实看到 this 可以在 TS 中的类型上下文中使用。知道我做错了什么吗?

标签: typescriptpolymorphismes6-promise

解决方案


TypeScript 为此具有多态 this类型。

您可以将this其用作类型,例如声明具有Promise<this>类型的东西,它可以按预期工作:

class foo {
  aFoo(): Promise<this> {
    return new Promise<this>(resolve => resolve(this));
  }
}

class bar extends foo {
  test() {
    this.aFoo().then(result => {
      let val: bar;
      val = result;// OK, this is bar here;
    });
  }
}

推荐阅读