简体   繁体   中英

Typescript does not allow an extended class promise to be the return type of an async function

I have got a class that is extended from the global Promise class and should have some additional normal and async functions. The normal functions like "init" are working but the async one like "doSomething" are not.

It always throws the following typescript error:

The return type of an async function or method must be the global Promise type.

I don't know why it isn't working. Here is the code I'm working on.

class MyPromise<T> extends Promise<T> {
    private somedata = {};

    constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
        super(executor);
    }

    public static init<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): MyPromise<T> {
        return new MyPromise(executor);
    }

    public async doSomething(fnc: () => Promise<number>): MyPromise<T> {
        this.somedata = await fnc();

        return this;
    }
}

Update: @Evert was right, it was a XY problem.

An async function returns a built-in Promise. Changing the return type of the function does not alter this.

So you must change MyPromise<T> to Promise<T> , or not use async .

You can of course still return MyPromise, it just means that you need to stop using async.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM