打字稿中的多态承诺

时间:2019-08-03 22:31:25

标签: typescript polymorphism es6-promise

我正在尝试在Typescript类中对返回Promise的函数进行参数化。完成承诺后,我将返回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;
    });
  }
}

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

错误提示:

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中的怪异有关,但是将其更改为箭头功能并不能消除错误。这个错误也让我感到奇怪,因为它描述的是一种类型,而不是实例,但是我确实看到它可以在TS的类型上下文中使用。知道我在做什么错吗?

1 个答案:

答案 0 :(得分:3)

TypeScript为此具有polymorphic 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;
    });
  }
}