TypeScript subclass of Promise cannot be used as async function return value for ES6+

Viewed 87

index.ts:

class MyPromise<T> extends Promise<T>{
}

async function testFn1(): MyPromise<void> {
    return new MyPromise(resolve => resolve());
}

Take the above code snippet as an example. TypeScript gives the following compilation error when I set target to ES6 or later, using tsc --target es6 index.ts.

error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<T>'?

However, there will be no compilation error if I use tsc --target es5 index.ts to compile.

Why is that?

1 Answers

An async function will always return a native Promise. Defining a subclass doesn't change that. What your testFn1 returns is a Promise<MyPromise<void>>.

Related