打字稿:subclass/extend of Promise:不引用与 Promise 兼容的构造函数值

Typescript: subclass/extend of Promise: does not refer to a Promise-compatible constructor value

我正在尝试取消我在 Typescript 中的 async 方法调用。

为此,我创建了一个新的 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.

如果我使用类型声明和 return CancelablePromise,那么它会编译:

async postFileAjax<T>(file: File): Promise<T>  { 
     ...
     return CancelablePromise(...);
}

我做错了什么?我看到在 ES6 中你可以将 Promise 子类化(参见 ),所以我希望在 TypeScript 中它也可以。

使用 Typescript 2.1 并以 es5 为目标

起初我并没有完全清楚错误信息,但是构造函数的签名应该Promise的构造函数完全相同。

我已经从构造函数中删除了 cancelMethod 并将在稍后设置它。这有效:

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;
}