Lexermal
Lexermal

Reputation: 43

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.

Upvotes: 4

Views: 1515

Answers (1)

Evert
Evert

Reputation: 99533

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.

Upvotes: 4

Related Questions