Borislav Hadzhiev
Thu Feb 24 2022·2 min read
Photo by Robson Hatsukami Morgan
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.
// 👇️ 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.
// 👇️ 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.
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.
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
.
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>>;