2 min read

TypeScript Awaited Type

The Awaited<Type> utility type (introduced in TypeScript 4.5) is designed to model the operation of await in async functions, or the .then() method on Promises. It recursively unwraps the type of a Promise to reveal the final result.

1. Basic Usage

If you have a Promise<string>, Awaited extracts the string.

type A = Awaited<Promise<string>>;
// type A = string

2. Recursive Unwrapping

One of the key features of Awaited is that it handles nested Promises. If you have a Promise that resolves to another Promise, Awaited digs all the way down to the final value, just like runtime await does.

type B = Awaited<Promise<Promise<number>>>;
// type B = number

type C = Awaited<boolean | Promise<number>>;
// type C = boolean | number

3. Handling Non-Promise Values

If you pass a type that isn't a Promise, Awaited returns the type itself.

type D = Awaited<number>;
// type D = number

4. Use Case: Getting the Return Type of an Async Function

Combined with ReturnType, Awaited is very useful for getting the final resolved value of an async function without executing it.

async function fetchData() {
    return { id: 1, name: "Alice" };
}

// ReturnType gives Promise<{ id: number, name: string }>
// Awaited unwraps it to { id: number, name: string }
type Data = Awaited<ReturnType<typeof fetchData>>;

5. How it works

Under the hood, Awaited uses conditional types and infer to recursively unwrap the type. It checks if the type has a then method (is a "Thenable") and infers the argument of the callback.

// Simplified conceptual implementation
type MyAwaited<T> = T extends PromiseLike<infer U> ? MyAwaited<U> : T;

programming/javascript/typescript/typescript programming/javascript/typescript/utility-types programming/javascript/typescript/infer-keyword