0
我试图在Typescript中取消我的async
方法调用。Typescript:Promise的子类/扩展:不引用Promise兼容的构造函数值
要做到这一点,我创建了一个新的承诺类型,它继承了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();
}
}
}
但是,当我试图使用它:
async postFileAjax<T>(file: File): CancelablePromise<T> { ... }
我得到的错误:
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
,像这样然后它编译:
async postFileAjax<T>(file: File): Promise<T> {
...
return CancelablePromise(...);
}
我做错了什么?我看到在ES6中,您可以继承Promise
(请参阅stackoverflow question),所以我期望它也可以在TypeScript中使用。
使用打字稿2.1和定位ES5
不能扩展内建类型,除非你的目标'es6'(或以上) –
如果你有一个参考,然后这是公认的答案;) – Julian
试试这个:[扩展错误在发射ES5时不起作用](https://github.com/Microsoft/TypeScript/issues/10166) –