Sub topic 9
Recursive mapped types: building DeepReadonly
This chapter assumes you know generics, mapped types with keyof, conditional types with extends, and the basics of infer. It builds one utility, DeepReadonly, and uses it to show how a mapped type can refer to itself. It also covers the cases where a naive version breaks.
Why `readonly` is shallow
The built-in Readonly<T> adds readonly to the properties of T, one level deep. It leaves nested objects and arrays alone.
type Config = {
name: string;
server: { host: string; ports: number[] };
};
declare const config: Readonly<Config>;
// config.name = 'x'; // error: read-only property
config.server.host = 'x'; // allowed: the nested object is still mutable
config.server.ports.push(80); // allowed: the nested array is still mutableTo freeze every level, the mapped type has to apply itself to each property type. That is a recursive type alias: DeepReadonly appears inside its own definition.
The first version
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
type FrozenConfig = DeepReadonly<Config>;The type has three branches:
- Functions are returned unchanged.
- Objects (including arrays and tuples) are mapped. Each property gets
readonly, and its type is run throughDeepReadonlyagain. - Everything else (primitives such as
string,number,boolean,null,undefined) is the base case. It is returned as is, so the recursion stops there.
const frozen: FrozenConfig = {
name: 'app',
server: { host: 'localhost', ports: [80, 443] },
};
// frozen.server.host = 'x'; // error: read-only property
// frozen.server.ports.push(1) // error: 'push' does not exist on 'readonly number[]'
// frozen.server = frozen.server; // error: 'server' is read-only
console.log(frozen.server.ports[0]); // 80Run tsc --noEmit on this file. The three commented lines each produce an error when uncommented.
How the recursion terminates
Every recursive step moves from a type to the type of one of its properties. The type has finitely many levels, so the walk ends. It ends at a primitive or at a function, because neither branch recurses.
The block above is only a placeholder to avoid confusion; the real diagram follows.
Why each branch exists
Why functions are special-cased
A function type is an object type, so without the first branch it would reach the mapped type. A mapped type over a function type keeps only the function's own properties, and there are none to keep. The call signature is lost, and the result is an empty object type {}. The first branch prevents that.
type Broken<T> = T extends object ? { readonly [K in keyof T]: Broken<T[K]> } : T;
type Handler = (id: number) => void;
type H = Broken<Handler>; // {} : no longer callableHow arrays and tuples are handled
When keyof T is mapped over a type parameter that is instantiated with an array or tuple, TypeScript treats the mapped type as homomorphic. It maps the elements and keeps the array or tuple shape, and readonly turns the array into a readonly array. You don't need a special branch.
type A = DeepReadonly<{ tags: string[]; pair: [number, { id: string }] }>;
// {
// readonly tags: readonly string[];
// readonly pair: readonly [number, { readonly id: string }];
// }Why unions work
The check T extends (...args: any[]) => any is a conditional type on a bare type parameter, so it distributes over unions (see the earlier chapter on distribution). A property typed { a: string } | undefined is processed member by member. The object member is frozen and undefined passes through the base case.
type Opt = DeepReadonly<{ user?: { name: string } | null }>;
// { readonly user?: { readonly name: string } | null | undefined }Why modifiers survive
A mapped type of the form { [K in keyof T]: ... } where T is a type parameter is homomorphic. It copies the optional (?) and readonly modifiers from T. That is why user? stays optional in the example above.
Recursive types and laziness
A type alias normally can't refer to itself directly. A reference is allowed when it sits inside an object type, a mapped type, or an array or tuple position, because TypeScript resolves those parts lazily. That is the reason DeepReadonly is legal. The recursive call is inside the property type of a mapped type, and it is only evaluated when someone looks at that property.
This also lets DeepReadonly handle types that are themselves recursive.
type TreeNode = {
value: number;
children: TreeNode[];
};
type FrozenTree = DeepReadonly<TreeNode>;
declare const tree: FrozenTree;
const first = tree.children[0]; // FrozenTree-like node, itself readonly
// first.children.push(first); // error: 'push' does not exist on a readonly array
// first.value = 3; // error: read-only propertyThe type does not expand forever. TypeScript produces DeepReadonly<TreeNode> once, and the property children refers back to that same instantiation.
Handling Map, Set and other classes
The simple version has a weakness. A Map is an object, so it goes through the mapped type. The mapped type keeps Map's methods, including set and delete, and only marks the property slots readonly. The map can still be mutated. To fix this, map Map and Set to their read-only interfaces.
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 Registry = { users: Map<string, { name: string }>; ids: Set<number> };
declare const registry: DeepReadonly<Registry>;
const user = registry.users.get('a'); // { readonly name: string } | undefined
// registry.users.set('b', { name: 'B' }); // error: 'set' does not exist
// registry.ids.add(4); // error: 'add' does not existHere infer and recursion work together. infer K and infer V capture the key and value types of the map, and the recursive call freezes them.
Other built-in objects such as Date or Promise pass through the object branch. Their methods stay callable, because methods are function-typed properties that hit the first branch. Date.prototype.setFullYear therefore still exists on a DeepReadonly<Date>. If you need to protect such types, add a branch that returns them unchanged or maps them to a read-only equivalent that you define.
Variations on the same pattern
Swapping the modifier gives other utilities. A - before a modifier removes it, and ? adds optionality.
type DeepMutable<T> = T extends (...args: any[]) => any
? T
: T extends object
? { -readonly [K in keyof T]: DeepMutable<T[K]> }
: T;
type DeepPartial<T> = T extends (...args: any[]) => any
? T
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
type Patch = DeepPartial<{ server: { host: string; port: number } }>;
const patch: Patch = { server: { port: 8080 } }; // host can be left outGotchas
| Situation | What happens | What to do |
|---|---|---|
| Function-typed property | Without a function branch, the call signature is lost and the type becomes `{}` | Keep the `extends (...args: any[]) => any ? T` branch first |
| `Map` and `Set` | `set`, `add` and `delete` stay callable | Map them to `ReadonlyMap` and `ReadonlySet` |
| `DeepReadonly<T>` assigned to `T` | Readonly arrays are rejected, so the assignment fails | Treat the frozen type as a view. Copy the value, or use `DeepMutable` |
| Mutable target of a readonly object | Plain `readonly` properties are assignable to mutable ones, so a `readonly` object type can be assigned to a mutable one | Do not rely on `readonly` as a security boundary |
| Runtime behavior | `readonly` is erased when compiled, and values are not frozen | Use `Object.freeze` recursively if you need runtime protection |
| Very large or deeply nested types | Instantiation depth limits or slow compile times | Keep types shallow, or test with realistic data |
Putting the pieces together
Here is a complete file you can compile. It combines the function branch, the collection branches and the object branch, and it uses an assertion helper from the last chapter of this tutorial to confirm the result.
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 Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type Input = { a: { b: string[] }; run: () => void };
type Expected = {
readonly a: { readonly b: readonly string[] };
readonly run: () => void;
};
type _Check = Expect<Equal<DeepReadonly<Input>, Expected>>;
function describe(input: DeepReadonly<Input>): string {
return input.a.b.join(',');
}
console.log(describe({ a: { b: ['x', 'y'] }, run: () => {} })); // x,yIf you change Expected, for example by dropping the inner readonly on b, the _Check line becomes a compile error.
Exercise
Write DeepRequired<T>, which removes optionality from every property at every level. Functions and primitives must be left unchanged. What changes compared with DeepReadonly, and what should DeepRequired<{ a?: { b?: number } }> produce?
Show answer
Replace the modifier in the mapped type with -?: type DeepRequired<T> = T extends (...args: any[]) => any ? T : T extends object ? { [K in keyof T]-?: DeepRequired<T[K]> } : T;. The function branch and the base case stay as they are. The result for { a?: { b?: number } } is { a: { b: number } }. Because of -?, the undefined that optionality adds to each property type is also removed, so the inner types are plain { b: number } and number.
Exercise
Why does DeepReadonly need a branch that returns function types unchanged? What would DeepReadonly<(id: number) => void> become without it?
Show answer
A mapped type over a function type keeps only the function's own properties, so the call signature disappears. Without the branch the result would be {}, and the value could no longer be called. With the branch, the function type is returned as is.
Exercise
A teammate says DeepReadonly<Config> guarantees that nobody changes a config object at runtime. Give two reasons this is wrong.
Show answer
First, readonly is erased at compile time, so the emitted JavaScript does not freeze anything. Second, casts to any, plain JavaScript callers and code that is not type-checked can still mutate the object. Readonly properties are also assignable to mutable ones in TypeScript, so a frozen type can leak into a mutable one. Use Object.freeze recursively when runtime protection is needed.