Sub topic 11
Recursive Types: DeepReadonly and Awaited
This chapter assumes you can read and write generics with constraints, and that you know mapped types ({ [K in keyof T]: ... }), conditional types (T extends U ? X : Y) and infer from the earlier chapters. Here you combine them with recursion. A type alias refers to itself, and the compiler expands it until it reaches a base case.
Why types need recursion
Real data is nested. A configuration object holds objects, which hold arrays of objects. A promise can resolve to another promise. A single mapped or conditional type only looks one level down. To handle arbitrary depth, the type has to call itself on the parts it finds, the same way a recursive function does.
A recursive type needs the same two things as a recursive function:
- A base case that returns a result without recursing.
- A recursive case that applies the type to a smaller piece of the input.
Recursive conditional types: building Awaited
await unwraps a promise, and if the result is another promise it keeps unwrapping. A conditional type with infer can match one layer. Recursion repeats that match until nothing is left to unwrap.
type MyAwaited<T> = T extends PromiseLike<infer U> ? MyAwaited<U> : T;
type A = MyAwaited<Promise<number>>; // number
type B = MyAwaited<Promise<Promise<string>>>; // string
type C = MyAwaited<boolean>; // boolean
type D = MyAwaited<Promise<string> | Promise<number>>; // string | numberHere is how MyAwaited<Promise<Promise<string>>> expands:
Promise<Promise<string>>matchesPromiseLike<infer U>, soUisPromise<string>. The result isMyAwaited<Promise<string>>.Promise<string>matches again, withUasstring. The result isMyAwaited<string>.stringdoes not matchPromiseLike<...>. The false branch is the base case and returnsstring.
Case D works because T is a naked type parameter, so the conditional distributes over the union. Each member is unwrapped separately and the results are joined.
The built-in Awaited<T> is more careful than this version. It checks for any object with a callable then method, and it extracts the type of the first argument passed to the then callback. It also leaves non-thenable objects alone. PromiseLike covers most real cases, but your version can differ from the built-in one for unusual thenables. For production code, use Awaited.
Recursive mapped types: building DeepReadonly
Readonly<T> only marks the top-level properties as readonly. Nested objects stay mutable:
type Settings = { ui: { theme: string }; tags: string[] };
const s: Readonly<Settings> = { ui: { theme: "dark" }, tags: ["a"] };
s.ui.theme = "light"; // allowed: only the top level is readonlyTo protect every level, the mapped type must apply itself to each property type. The recursion happens inside the property position:
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
type Settings = { ui: { theme: string }; tags: string[] };
const settings: DeepReadonly<Settings> = {
ui: { theme: "dark" },
tags: ["a", "b"],
};
settings.ui.theme = "light"; // error: Cannot assign to 'theme' because it is a read-only property.
settings.tags.push("c"); // error: Property 'push' does not exist on type 'readonly string[]'.The type has three outcomes, and the first two are base cases:
| Input `T` | Branch taken | Result |
|---|---|---|
| A function | First conditional | `T` unchanged |
| A primitive such as `string` | Final false branch | `T` unchanged |
| An object, array or tuple | Mapped type | Readonly properties, each passed through `DeepReadonly` |
Why functions get their own branch
A function type satisfies T extends object. Without the first branch, a method would be mapped over its own keys. The mapped type has no call signature, so a method such as save(): void would turn into a plain object type that cannot be called. Returning functions unchanged keeps them callable.
Arrays and tuples
When a homomorphic mapped type (one of the form { [K in keyof T]: ... } over a type parameter) is instantiated with an array or tuple, TypeScript maps the elements and keeps the array shape. It does not map the array's methods. With the readonly modifier, string[] becomes readonly string[], and [number, string] becomes readonly [number, string]. That is why push disappears in the example above. You get this without writing any array-specific branch.
Unions and self-referencing data
The check T extends object distributes over unions, so DeepReadonly<string | { a: number }> becomes string | { readonly a: number }.
Recursive data types work too. Mapped types are evaluated lazily, so the compiler does not expand the whole structure up front:
type Tree = { value: number; children: Tree[] };
const tree: DeepReadonly<Tree> = {
value: 1,
children: [{ value: 2, children: [] }],
};
tree.children[0].value = 5; // error: Cannot assign to 'value' because it is a read-only property.Handling Map, Set and Date
DeepReadonly as written maps over the keys of a Map. The mapped type keeps its methods because functions are returned unchanged, so map.set(...) still compiles. The readonly modifier does not stop that call. Add branches for the built-in collections before the generic object branch:
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends ReadonlyMap<infer K, infer V>
? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
: T extends ReadonlySet<infer U>
? ReadonlySet<DeepReadonly<U>>
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
type Cache = DeepReadonly<Map<string, { hits: number }>>;
// ReadonlyMap<string, { readonly hits: number }>A Map is assignable to ReadonlyMap, so the infer match succeeds. The result type has no set or delete. The order of the branches matters, because the generic object branch would also match a Map and must come last.
Date has mutating methods such as setFullYear. You can handle it with a branch like T extends Date ? Readonly<T> : ..., but Readonly<Date> does not remove those methods either. Many teams treat Date as an opaque leaf and return it unchanged, or store timestamps as numbers.
Recursion limits
The compiler caps how deep type instantiation can go. A recursive type that runs too long fails with error TS2589, "Type instantiation is excessively deep and possibly infinite." The limit for ordinary recursion is on the order of 100 levels, depending on the version. That is plenty for object nesting, but it can bite when you recurse once per element of a long tuple or once per character of a string.
Since TypeScript 4.5, a conditional type in tail position gets a much higher limit, around 1000 levels. A recursive call is in tail position when the whole branch is that call, with nothing wrapped around it. Carrying the result in an accumulator parameter is the usual way to get there:
type Range<N extends number, Acc extends number[] = []> =
Acc["length"] extends N ? Acc : Range<N, [...Acc, Acc["length"]]>;
type Zero = Range<0>; // []
type Three = Range<3>; // [0, 1, 2]Each step grows Acc by one element. The recursive call is the whole false branch, so the compiler can reuse the frame. If you wrote [Acc["length"], ...Range<...>] instead, the call would be wrapped in a tuple, and you would get the lower limit.
Common mistakes
- Forgetting the base case. A recursive alias with no branch that stops the recursion gives a circularity or depth error. In
DeepReadonly, the primitive fallback is what ends the recursion. - Putting the function check after the object check. Functions are objects, so they would be mapped and lose their call signatures.
- Expecting recursion through
any.DeepReadonly<any>does not recurse into anything useful. A check onanyevaluates to the union of both branches of the conditional type. - Recursing directly in a type alias that is not deferred. An alias such as
type Bad<T> = Bad<T>is rejected. Recursion is allowed when it passes through an object type, a mapped type, or a conditional branch, because those are evaluated lazily.
Exercise
Write DeepPartial<T> that makes every property optional at every depth, leaving functions and primitives unchanged. Then say what DeepPartial<{ a: { b: number } }> produces.
Show answer
type DeepPartial<T> = T extends (...args: any[]) => any ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T; The example produces { a?: { b?: number } }. The function branch and the primitive fallback are the base cases, and the mapped type with the ? modifier is the recursive case.
Exercise
Why does Range<3> use an accumulator Acc, and what would change if the false branch were [...Range<N, [...Acc, Acc["length"]]>]?
Show answer
The accumulator carries the partial result forward, so the recursive call is the entire false branch. That is tail position, which allows a depth of about 1000. Wrapping the call in a tuple spread moves it out of tail position, so the compiler applies the lower depth limit and long inputs can fail with TS2589.
Exercise
What does MyAwaited<Promise<number> | string> evaluate to, and which feature of conditional types causes it?
Show answer
It evaluates to number | string. T is a naked type parameter, so the conditional type distributes over the union. Promise<number> unwraps to number through one recursive step, and string takes the false branch unchanged.