打字稿:Promise 的子类/扩展:不引用与 Promise 兼容的构造函数值 [英] Typescript: subclass/extend of Promise: does not refer to a Promise-compatible constructor value
问题描述
我正在尝试取消我在 Typescript 中的 async
方法调用.
I'm trying to cancel my async
method call in Typescript.
为此,我创建了一个新的 Promise 类型,它继承自 Promise
:
To do this, I have created a new Promise type, which inherits from Promise
:
class CancelablePromise<T> extends Promise<T>{
private cancelMethod: () => void;
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void, cancelMethod: () => void) {
super(executor);
this.cancelMethod = cancelMethod;
}
//cancel the operation
public cancel() {
if (this.cancelMethod) {
this.cancelMethod();
}
}
}
但是当我尝试使用它时:
But when I'm trying to use it:
async postFileAjax<T>(file: File): CancelablePromise<T> { ... }
我收到错误:
Error Build:Type 'typeof CancelablePromise' 不是 ES5/ES3 中有效的异步函数返回类型,因为它不引用与 Promise 兼容的构造函数值.
Error Build:Type 'typeof CancelablePromise' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.
如果我使用类型声明并返回 CancelablePromise
,就像这样,它会编译:
If I using the type declaration and return the CancelablePromise
, like this then it compiles:
async postFileAjax<T>(file: File): Promise<T> {
...
return CancelablePromise(...);
}
我做错了什么?我看到在 ES6 中你可以将 Promise
子类化(参见 stackoverflow 问题),所以我会期待它也在 TypeScript 中.
What am I doing wrong? I see that in ES6 you could subclass the Promise
(see stackoverflow question), so I would expect it also in TypeScript.
使用 Typescript 2.1 并定位 es5
Using Typescript 2.1 and targeting es5
推荐答案
一开始我并没有完全清楚错误信息,但是构造函数的签名应该完全相同Promise
的构造函数.
The error message wasn't fully clear to me at first, but the signature of the constructor should be completely the same as the constructor of Promise
.
我已经从构造函数中删除了 cancelMethod
并将在稍后设置它.这有效:
I've removed the cancelMethod
from the constructor and will set it later. This works:
class CancelablePromise<T> extends Promise<T>{
public cancelMethod: () => void;
constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
super(executor);
}
//cancel the operation
public cancel() {
if (this.cancelMethod) {
this.cancelMethod();
}
}
}
并调用:
async postFileAjax<T>(file: File): CancelablePromise <T> {
var promiseFunc = (resolve) => { resolve() };
var promise = new CancelablePromise<T>(promiseFunc);
promise.cancelMethod = () => { console.log("cancel!") };
return promise;
}
这篇关于打字稿:Promise 的子类/扩展:不引用与 Promise 兼容的构造函数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!