Get the return Type of a Promise in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 24, 2022

banner

Photo from Unsplash

Get the return Type of a Promise in TypeScript #

Use the Awaited utility type to get the return type of a promise in TypeScript, e.g. type A = Awaited<Promise<string>>. The Awaited utility type is used to recursively unwrap Promises and get their return type.

index.ts
// 👇️ type A = string type A = Awaited<Promise<string>>; // 👇️ type B = string type B = Awaited<Promise<Promise<string>>>; // 👇️ C = boolean | number type C = Awaited<boolean | Promise<number>>; async function sum(a: number, b: number): Promise<number> { return a + b; } // 👇️ type D = number type D = Awaited<ReturnType<typeof sum>>;

We used the Awaited utility type to get the return type of a couple of Promises in the examples.

The type is used to recursively unwrap a Promise and get its return type.

The second example shows that we can unwrap the type of the promise even if it's nested.

index.ts
// 👇️ type B = string type B = Awaited<Promise<Promise<string>>>;

If you need to unwrap the return type of a promise from a function's return type, use the ReturnType utility type.

index.ts
function multiply(a: number, b: number): Promise<number> { return Promise.resolve(a * b); } // 👇️ type E = number type E = Awaited<ReturnType<typeof multiply>>;

The ReturnType utility type constructs a type consisting of the function's return type.

You can use the same approach to unwrap the return type of an async function. Note that async functions always return a Promise.

index.ts
async function sum(a: number, b: number): Promise<number> { return a + b; } // 👇️ type D = number type D = Awaited<ReturnType<typeof sum>>;

This approach also works with built-in methods like Promise.all and Promise.race.

index.ts
async function getArr(a: number, b: number): Promise<[number, string]> { const result = await Promise.all([ Promise.resolve(5), Promise.resolve('hello'), ]); return result; } // 👇️ [number, string] type E = Awaited<ReturnType<typeof getArr>>;
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.