typescript - 打字稿中的多态承诺
问题描述
我正在尝试在返回 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 中的类型上下文中使用。知道我做错了什么吗?
解决方案
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;
});
}
}
推荐阅读
- python - 由于缺少发布文件,无法安装 SQAOD Python 模块
- python - 如何使用python将本地html文件中的信息保存在文本文档中?
- php - 如何在 Baikal 上的用户之间共享日历?
- oracle - Oracle CREATE USER 权限
- next.js - 从“下一个/路由器”导入路由器可以吗?
- python - Docker 和 Django – 让一切保持最新和安全
- c# - 使子应用程序独立于 iis 10 中的根应用程序
- python - Python:添加正确的年初至今值
- javascript - Javascript 变量范围混淆的不寻常情况
- numpy - 如何使用存储为 .npy 文件的预训练模型?