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

折月煮酒 提交于 2019-12-05 00:59:12

问题


I'm trying to cancel my async method call in Typescript.

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> { ... }

I get the error:

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.

If I using the type declaration and return the CancelablePromise, like this then it compiles:

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

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.

Using Typescript 2.1 and targeting es5


回答1:


The error message wasn't fully clear to me at first, but the signature of the constructor should be the same the constructor of Promise. So this will compile:

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

and call:

async postFileAjax<T>(file: File): CancelablePromise <T> { 

    var promiseFunc = (resolve) => { resolve() };
    var promise = new CancelablePromise<T>(promiseFunc);
    promise.cancelMethod = () => { console.log("cancel!") };

    return promise;
}


来源:https://stackoverflow.com/questions/43327229/typescript-subclass-extend-of-promise-does-not-refer-to-a-promise-compatible-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!