Sub topic 8
Recursive conditional types: unwrapping nested Promises
This chapter assumes you know generics, union types, and function type signatures. It also assumes you have seen a basic conditional type (T extends U ? X : Y) and the infer keyword from the earlier chapters. Here you combine the two. A conditional type calls itself on the type it just extracted, and it stops when the input no longer matches.
Why one level of unwrapping is not enough
You can pull the result type out of a Promise with one infer:
type UnwrapOnce<T> = T extends PromiseLike<infer U> ? U : T;
type A = UnwrapOnce<Promise<string>>; // string
type B = UnwrapOnce<Promise<Promise<number>>>; // Promise<number>B is still a Promise. The conditional type matched once and returned U, which happens to be another Promise. Nothing checks the result again. At runtime, await keeps going until the value is not a Promise. To get the same behavior at the type level, the alias has to refer to itself.
The recursive version
type UnwrapPromise<T> = T extends PromiseLike<infer U> ? UnwrapPromise<U> : T;
type R1 = UnwrapPromise<Promise<Promise<number>>>; // number
type R2 = UnwrapPromise<string>; // stringA recursive conditional type has two parts:
- The recursive branch (the "true" branch). When
TmatchesPromiseLike<infer U>, the alias calls itself with the extractedU. - The base case (the "false" branch). When
Tdoes not match, the alias returnsTas it is. This is what ends the recursion.
If a recursive alias has no branch that stops, TypeScript reports an error such as "Type instantiation is excessively deep and possibly infinite" when it expands the type. The base case is not optional.
Tracing the evaluation
The compiler evaluates UnwrapPromise<Promise<Promise<number>>> in these steps:
Promise<Promise<number>>extendsPromiseLike<infer U>, soUisPromise<number>. The result isUnwrapPromise<Promise<number>>.Promise<number>extendsPromiseLike<infer U>, soUisnumber. The result isUnwrapPromise<number>.numberdoes not extendPromiseLike<...>, so the false branch returnsnumber.
Checking the result in a runnable file
You can confirm the behavior with assignments that the compiler checks:
type UnwrapPromise<T> = T extends PromiseLike<infer U> ? UnwrapPromise<U> : T;
declare function loadNested(): Promise<Promise<number>>;
type Loaded = UnwrapPromise<ReturnType<typeof loadNested>>;
const ok: Loaded = 42;
// @ts-expect-error Loaded is number, not string
const bad: Loaded = "42";
console.log(ok, bad);The @ts-expect-error comment makes the compiler fail if the next line is not an error. That makes it a cheap way to test a type. A later chapter covers more reliable assertions.
Behavior on unions
UnwrapPromise<T> is a distributive conditional type. T is a bare type parameter on the left of extends, so a union is split into its members. Each member is evaluated separately, and the results are joined into a union again.
type UnwrapPromise<T> = T extends PromiseLike<infer U> ? UnwrapPromise<U> : T;
type Mixed = UnwrapPromise<Promise<number> | string | Promise<Promise<boolean>>>;
// number | string | booleanThis is what you want here, because Promise<number> | string is the type of a value you might await. Two consequences follow from distribution:
UnwrapPromise<never>isnever. A union with no members produces no results.- Wrapping the checked type in a tuple, as in
[T] extends [PromiseLike<infer U>], turns distribution off. The whole union is then checked as a single type. This is almost never what you want for unwrapping, but you need it when you must tellneverapart from other types.
Why the built-in Awaited is more elaborate
TypeScript 4.5 added the built-in Awaited<T>. It is also a recursive conditional type. Here is the same idea written the way the standard library writes it:
type MyAwaited<T> =
T extends null | undefined
? T
: T extends object & { then(onfulfilled: infer F, ...args: infer _): any }
? F extends (value: infer V, ...args: infer _) => any
? MyAwaited<V>
: never
: T;
type X = MyAwaited<Promise<Promise<number>>>; // number
type Y = MyAwaited<{ then(cb: (v: string) => void): void }>; // string
type Z = MyAwaited<null | Promise<boolean>>; // boolean | nullIt differs from UnwrapPromise in three ways:
- It checks the
thenmethod directly.awaitworks on any object with athenmethod (a "thenable"), not only on types that declarePromiseLike. Theobject & { then(...) }pattern matches that rule. - It passes
nullandundefinedthrough first. Without that branch, a nullable type would fall into the object check and behave unpredictably under strict settings. - It reads the callback's parameter.
Fis the type of theonfulfilledcallback. A secondinfer Vinside it pulls out the value the callback receives, and that value is what gets unwrapped next.
For everyday code, use the built-in Awaited. Write your own UnwrapPromise to learn the pattern, or when you need different rules, such as stopping at a specific wrapper type.
Where the recursion limit comes in
TypeScript does not expand a recursive type forever. Two limits matter:
- A recursive branch that does extra work after the self-call, for example
[UnwrapPromise<U>]orUnwrapPromise<U> | null, uses compiler stack. Those types fail after a limited number of levels (roughly a hundred, depending on the version) with an "excessively deep" error. - A recursive branch where the self-call is the whole result of that branch is a tail call. Since TypeScript 4.5, the compiler evaluates such types in a loop, and the limit is about 1000 levels.
UnwrapPromise is already in tail form: the true branch is only UnwrapPromise<U>. Real code seldom nests Promises more than a few levels, so you will not hit the limit here. The chapter on termination and limits returns to this with types that do recurse deeply.
Common mistakes
| Mistake | What happens | Fix | Column |
|---|---|---|---|
| No base case, or a base case that never matches | "Type instantiation is excessively deep" error | Make the false branch return `T` or another non-recursive type | |
| Using `Promise<infer U>` instead of `PromiseLike<infer U>` | Custom thenables are not unwrapped | Use `PromiseLike`, or the `then` pattern from `Awaited` | |
| Expecting `UnwrapPromise<A | B>` to check the union as a whole | It is evaluated per member | Wrap in a tuple, `[T] extends [...]`, if you need whole-union checking |
| Adding work after the self-call | Lower depth limit | Keep the self-call as the entire branch result | |
| Writing your own when `Awaited` fits | Subtle differences with `null`, `undefined`, and thenables | Use the built-in `Awaited` |
Applying the pattern to other wrappers
Nothing in the technique is specific to Promises. The structure is always: match a wrapper with infer, recurse on the inner type, and return the input unchanged when it no longer matches. Here is the same shape for nested arrays:
type DeepElement<T> = T extends readonly (infer U)[] ? DeepElement<U> : T;
type E1 = DeepElement<number[][][]>; // number
type E2 = DeepElement<(string | number[])[]>; // string | numberIn E2, the outer array is unwrapped to string | number[]. That union then distributes: string is the base case, and number[] unwraps to number.
Exercise
Write a recursive type UnwrapFn<T> that follows a chain of zero-argument functions that return functions, and returns the final non-function value. For example, UnwrapFn<() => () => string> should be string and UnwrapFn<number> should be number. Which part is the base case, and is your type in tail-recursive form?
Show answer
type UnwrapFn<T> = T extends () => infer R ? UnwrapFn<R> : T; The base case is the false branch, which returns T when T is not a zero-argument function. The type is in tail-recursive form because the true branch is only the call UnwrapFn<R>, with nothing added around it. For () => () => string, the first step gives R = () => string, the second gives R = string, and string does not match, so the result is string.
Exercise
What does UnwrapPromise<Promise<number> | Promise<Promise<string>>> evaluate to, and why? What does UnwrapPromise<never> evaluate to?
Show answer
The first type is number | string. UnwrapPromise is distributive, so each union member is unwrapped separately (number from the first, string from the second) and the results are combined into a union. UnwrapPromise<never> is never, because distributing over a union with no members produces no results.