Sub topic 8
Recursive conditional types: unwrapping nested Promises
Assume you know TypeScript generics, conditional types, function signatures, and basic Promise types. This chapter focuses on the working model for recursive conditional types and the common mistakes that make them fail.
The problem: nested asynchronous results
A Promise<T> represents a value that will be available later. The type parameter T is the promised result:
type User = {
id: number;
name: string;
};
type UserResult = Promise<User>;Sometimes a type contains several promise-like layers:
type NestedResult = Promise<Promise<User>>;You may want a utility type that removes every outer layer and returns the final result type. The utility should produce these results:
| Input type | Unwrapped type |
|---|---|
| `string` | `string` |
| `Promise<number>` | `number` |
| `Promise<Promise<boolean>>` | `boolean` |
A single conditional type can remove one layer. A recursive conditional type can repeat that operation.
Matching one layer with `infer`
A conditional type has the form T extends Pattern ? WhenTrue : WhenFalse. It checks whether T matches Pattern, then chooses one branch.
The infer keyword declares a type variable inside the pattern. TypeScript fills in that variable when the match succeeds:
type UnwrapOne<T> =
T extends PromiseLike<infer U>
? U
: T;
type A = UnwrapOne<Promise<number>>; // number
type B = UnwrapOne<string>; // stringFor Promise<number>, TypeScript matches T against PromiseLike<infer U>. It infers U as number, so the true branch returns number.
For string, the pattern does not match. The false branch returns the original type, string.
PromiseLike<T> is useful here because it also matches compatible thenable objects, not only native Promise<T> values.
Recursion and the base case
To remove every layer, the true branch calls the type alias again:
type UnwrapPromise<T> =
T extends PromiseLike<infer U>
? UnwrapPromise<U>
: T;
type R1 = UnwrapPromise<Promise<Promise<number>>>; // number
type R2 = UnwrapPromise<Promise<string>>; // string
type R3 = UnwrapPromise<Date>; // DateThe evaluation of UnwrapPromise<Promise<Promise<number>>> proceeds like this:
UnwrapPromise<Promise<Promise<number>>>
-> UnwrapPromise<Promise<number>>
-> UnwrapPromise<number>
-> numberThe final number does not match PromiseLike<infer U>. That false branch is the base case. A base case is the condition that stops recursion.
Unwrapping values and preserving non-Promise types
This utility changes types only. It does not change runtime values or wait for promises:
type UnwrapPromise<T> =
T extends PromiseLike<infer U>
? UnwrapPromise<U>
: T;
async function loadCount(): Promise<number> {
return 42;
}
type Count = UnwrapPromise<ReturnType<typeof loadCount>>; // number
const count: Count = 42;
console.log(count);ReturnType<typeof loadCount> is Promise<number>. UnwrapPromise extracts number.
The utility also preserves unions in many ordinary cases because the checked type is a naked type parameter. A union such as Promise<string> | number is evaluated member by member:
type Mixed = UnwrapPromise<Promise<string> | number>; // string | numberThis behavior is called distributive conditional typing.
Common errors
- Returning
Uinstead of recursing:T extends PromiseLike<infer U> ? U : Tremoves only one layer. - Forgetting the false branch: The type must define what happens for non-promises.
- Using a runtime function for a type-level problem:
awaitunwraps values at runtime, whileUnwrapPromisecomputes a type during compilation. - Recursing through arbitrary objects: Match only the structure you intend to unwrap. A broad pattern can transform unrelated types.
Exercise
What is the result of UnwrapPromise<Promise<Promise<{ id: number }>>>?
Show answer
{ id: number }. The type recursively removes two PromiseLike layers, then reaches the object base case.