Returning a promise in an async function in TypeScript

I understand that these two functions will have the same behavior in JavaScript:

const whatever1 = (): Promise<number> => { return new Promise((resolve) => { resolve(4); }); }; const whatever2 = async (): Promise<number> => { return new Promise((resolve) => { resolve(4); }); }; 

But TypeScript doesn't seem like the second, it says:

 Type '{}' is not assignable to type 'number'. 

Is this a mistake in TypeScript, or am I not understanding something about asynchronous functions?

+5
source share
2 answers

It's complicated.

First of all, in this code

 const p = new Promise((resolve) => { resolve(4); }); 

type p defined as Promise<{}> . There is an open problem about this on typescript github, so maybe this is a bug, because obviously (for humans) p should be Promise<number> .

Then Promise<{}> compatible with Promise<number> , because basically the only property that has a promise is the then method, and then compatible in these two types of promises according to the typescript function type compatibility rules . Therefore, there is no error in whatever1 .

But the goal of async is to pretend that you are dealing with actual values, not promises, and then you get an error in whatever2 because {} is obvioulsy incompatible with number .

So, the behavior of async is the same, but it currently needs some workaround to compile typescript. You can simply provide an explicit general argument when creating such a promise:

 const whatever2 = async (): Promise<number> => { return new Promise<number>((resolve) => { resolve(4); }); }; 
+11
source

When you execute new Promise((resolve)... , the type that was specified was Promise<{}> because you had to use new Promise<number>((resolve) .

Interestingly, this question was highlighted only when adding the async . I would recommend reporting this issue to the TS team on GitHub .

There are many ways around this problem. All of the following functions have the same behavior:

 const whatever1 = () => { return new Promise<number>((resolve) => { resolve(4); }); }; const whatever2 = async () => { return new Promise<number>((resolve) => { resolve(4); }); }; const whatever3 = async () => { return await new Promise<number>((resolve) => { resolve(4); }); }; const whatever4 = async () => { return Promise.resolve(4); }; const whatever5 = async () => { return await Promise.resolve(4); }; const whatever6 = async () => Promise.resolve(4); const whatever7 = async () => await Promise.resolve(4); 

In your IDE, you will see that the output type for all these functions is () => Promise<number> .

+4
source

All Articles