Typescript中的多态承诺

Typescript中的多态承诺,typescript,polymorphism,es6-promise,Typescript,Polymorphism,Es6 Promise,我正在尝试参数化Typescript类中返回承诺的函数。完成承诺后,我将返回调用方以多态方式使用的this。我得到了一个编译时错误,我不太明白 这段(平凡化的)代码编译得很好: class foo { aFoo(): Promise<foo> { return new Promise<foo>(resolve => resolve(this)); } } class bar extends foo { test() { this.aFoo

我正在尝试参数化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;
    });
  }
}
在aFoo返回的promise中,
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.
this:this
“this”类型的参数不能分配给“T | PromiseLike | undefined”类型的参数。
类型“foo”不可分配给类型“T | PromiseLike | undefined”。
类型“foo”不可分配给类型“PromiseLike”。
类型“this”不可分配给类型“PromiseLike”。
类型“foo”中缺少属性“then”,但类型“PromiseLike”中需要该属性。ts(2345)
lib.es5.d.ts(1393,5):“then”在这里声明。
我可以通过执行一些无关的强制转换来抑制编译器错误:

return new Promise<foo>(resolve => resolve((this as unknown) as T));
返回新承诺(resolve=>resolve((此为未知)为T));
我可以使用变通方法,但我想了解编译器反对什么。我认为这可能与JS/TS中的奇怪之处有关,但将其更改为箭头函数并没有消除错误。这个错误也让我感到奇怪,因为它将此描述为一个类型,而不是一个实例-但我确实看到,这可以在TS的类型上下文中使用。知道我做错了什么吗?

TypeScript为此提供了类型

您可以使用
this
作为一个类型,例如,声明某个具有
Promise
类型的内容,它可以按预期工作:

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;
    });
  }
}
class-foo{
承诺{
返回新承诺(resolve=>resolve(this));
}
}
类栏扩展了foo{
测试(){
this.aFoo().then(结果=>{
让瓦尔:酒吧;
val=result;//好的,这里是条;
});
}
}

任何东西都不能保证
属于
T
类型。您可以使用
this.aFoo()
,并且
this
将是bar类型,但T将是其他类型。
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;
    });
  }
}