Sub topic 12
Going deeper: a recursive DeepReadonly type
The built-in Readonly<T> locks only the top level of an object type. This chapter builds a recursive DeepReadonly<T> that locks every level, explains each part of its definition, and covers where it stops working. It also shows how to make the runtime behave the way the type claims.
This chapter assumes you know generics, conditional types (T extends U ? X : Y), mapped types ({ [K in keyof T]: ... }), and the shallow behavior of readonly from earlier chapters.
Why Readonly<T> is not enough
Readonly<T> adds readonly to each property of T. It does not look at the property types. A nested object or array stays fully mutable:
interface Settings {
ui: { theme: string; tags: string[] };
}
const s: Readonly<Settings> = { ui: { theme: "dark", tags: ["a"] } };
// s.ui = { theme: "light", tags: [] }; // Error: 'ui' is read-only
s.ui.theme = "light"; // allowed
s.ui.tags.push("b"); // allowedOnly the ui property is protected. Everything below it can still change. To protect every level, the transformation has to apply itself to each property type, which makes it recursive.
Building DeepReadonly step by step
Step 1: a naive recursive mapped type
The first attempt maps over the keys and calls itself on each property type:
type NaiveDeep<T> = { readonly [K in keyof T]: NaiveDeep<T[K]> };This already works for primitives. A mapped type that loops over keyof T for a type parameter T is called homomorphic. When T is a primitive such as string, a homomorphic mapped type returns it unchanged. Recursion therefore stops at the leaves without any extra check.
Functions are where it breaks. Mapping over a function type produces an object type with no call signature:
interface Api {
name: string;
fetch: () => void;
}
declare const api: NaiveDeep<Api>;
api.fetch(); // Error: This expression is not callable. Type '{}' has no call signatures.Step 2: leave functions alone
A conditional type that checks for function types fixes this. It also gives each case a visible branch:
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;The type has three outcomes:
- If
Tis a function, return it unchanged. - If
Tis any other object, which includes arrays and tuples, rebuild it with every propertyreadonlyand every property type passed throughDeepReadonly. - Otherwise
Tis a primitive, so return it unchanged.
Using it on the earlier Settings interface blocks all three mutations:
interface Settings {
ui: { theme: string; tags: string[] };
}
const s: DeepReadonly<Settings> = { ui: { theme: "dark", tags: ["a"] } };
// s.ui.theme = "light"; // Error: read-only
// s.ui.tags.push("b"); // Error: 'push' does not exist on type 'readonly string[]'The error for push appears because a homomorphic mapped type applied to an array type with readonly produces a readonly array. Settings["ui"]["tags"] is string[], so it becomes readonly string[]. You do not need a separate array branch.
What happens to arrays, tuples, unions and optional properties
Because the mapped type is homomorphic, it preserves the shape of whatever it is given:
- Arrays:
DeepReadonly<{ id: number }[]>becomesreadonly { readonly id: number }[]. The array and its elements are both locked. - Tuples:
DeepReadonly<[number, { a: string }]>becomesreadonly [number, { readonly a: string }]. Positions and lengths are preserved. - Optional properties:
?is kept.{ a?: { b: number } }becomes{ readonly a?: { readonly b: number } | undefined }. - Unions: The conditional type is distributive.
DeepReadonly<string | { n: number }>is evaluated once per union member and givesstring | { readonly n: number }.
type Row = DeepReadonly<[number, { label?: string }]>;
const row: Row = [1, { label: "x" }];
// row[0] = 2; // Error: Cannot assign to '0' because it is a read-only property.
// row[1].label = "y"; // Error: Cannot assign to 'label' because it is a read-only property.
// row.push(3); // Error: 'push' does not exist on type 'readonly [...]'.Gotchas: Map, Set, Date and class instances
The T extends object branch treats every non-function object as a bag of properties. That is wrong for built-in collections, because their mutation happens through methods, not through assignable properties.
For a Map, the mapped type makes set, get and delete readonly properties. Those properties still hold callable functions, so map.set(...) still compiles. The same applies to Set.add, to Date.setHours, and to any class whose methods mutate internal state.
The first fix is to add branches for ReadonlyMap and ReadonlySet, placed 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;
interface Cache {
byId: Map<number, { name: string }>;
seen: Set<string>;
}
declare const cache: DeepReadonly<Cache>;
// cache.byId.set(1, { name: "x" }); // Error: 'set' does not exist on type 'ReadonlyMap<...>'
// cache.seen.add("a"); // Error: 'add' does not exist on type 'ReadonlySet<string>'
const entry = cache.byId.get(1); // { readonly name: string } | undefinedA Map is assignable to ReadonlyMap, so the extends check matches. Put these branches before T extends object, or the object branch will capture maps first.
For Date and class instances there is no general answer. Options are:
- Add a
T extends Date ? Readonly<Date>style branch. This does not removesetHoursfrom the type, so it protects nothing. - Use
Omit<Date, \set${string}\>for dates. - Store a timestamp as a
numberor an ISO string and construct aDatewhen needed.
The last option is usually the cleanest.
Making the runtime match the type
readonly is erased at compile time, as an earlier chapter showed. A DeepReadonly<T> value is an ordinary mutable object at runtime. Code that casts the type away, or JavaScript code that never sees the type, can still change it.
To enforce the promise at runtime, combine the type with Object.freeze, applied recursively:
function deepFreeze<T extends object>(value: T): DeepReadonly<T> {
for (const key of Reflect.ownKeys(value)) {
const child = (value as Record<PropertyKey, unknown>)[key];
if (typeof child === "object" && child !== null && !Object.isFrozen(child)) {
deepFreeze(child);
}
}
return Object.freeze(value) as unknown as DeepReadonly<T>;
}
const config = deepFreeze({ ui: { theme: "dark", tags: ["a"] } });
// config.ui.tags.push("b"); // compile error, and a TypeError at runtime if the cast is bypassed
console.log(Object.isFrozen(config.ui.tags)); // trueThree details matter:
- The
unknowncast is deliberate.Object.freezereturnsReadonly<T>. TypeScript cannot prove that this equalsDeepReadonly<T>for an unresolvedT, so the function asserts it. The runtime loop is what makes the assertion true. - The
isFrozencheck prevents infinite loops. A cyclic object would otherwise recurse forever. - Frozen maps and sets are not immutable.
Object.freeze(new Map())freezes the map's own properties, butsetstill works because the entries live in internal slots. If you need a map that cannot change, copy it into a plain object or an array of entries before freezing.
How the result interacts with assignability
Recall that readonly on a property does not affect assignability. Arrays are the exception, and DeepReadonly makes arrays readonly. A value of type DeepReadonly<Settings> is therefore not assignable back to Settings if it contains arrays:
interface Settings {
ui: { theme: string; tags: string[] };
}
declare const frozen: DeepReadonly<Settings>;
const theme: string = frozen.ui.theme; // fine: reading a primitive
// const tags: string[] = frozen.ui.tags;
// Error: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
const tags: readonly string[] = frozen.ui.tags; // fineThis is a feature. The compiler stops code from passing the data to a function that would mutate it. The cost is that every function receiving the data must declare readonly parameters. Third-party functions that accept string[] but never mutate it will reject your arrays, and you will need a copy such as [...frozen.ui.tags] or a cast.
When to use it and when not to
| Situation | Better choice |
|---|---|
| Literal data written in your source, such as a list of options | `as const`, which is deeply readonly with no extra type |
| One level of protection is enough | `Readonly<T>` or `readonly T[]` |
| A large configuration object passed around the program | `DeepReadonly<T>`, optionally with `deepFreeze` at load time |
| Immutable updates of large state trees | A library such as Immer, which exports its own `Immutable<T>` type and handles structural sharing |
| Types with many class instances or `Date` values | Avoid `DeepReadonly`, or convert such values to plain data first |
Recursive types have a compile-time cost. On very large or deeply nested types, such as generated API schemas, DeepReadonly can slow the checker or hit instantiation depth limits. If your editor becomes sluggish, apply it only at the boundary where the data enters your program, not on every function signature.
Exercises
Exercise
Given type A = DeepReadonly<{ items: { id: number }[]; onSave: () => void }>, which of these statements compile: a.items[0].id = 2, a.items.push({ id: 3 }), a.onSave()?
Show answer
Only a.onSave() compiles. items becomes readonly { readonly id: number }[], so assigning id fails and push does not exist on a readonly array. The function branch returns () => void unchanged, so it remains callable.
Exercise
You remove the ReadonlyMap branch from DeepReadonly and apply it to { m: Map<string, number> }. Why can code still call value.m.set("a", 1), and what does the Map branch change?
Show answer
Without the branch, Map falls into the T extends object case, which only makes its properties readonly. set is a property holding a function, and making that property readonly does not stop it from being called. With the branch, m becomes ReadonlyMap<string, number>, a type that has no set, delete or clear methods.
Exercise
Why does deepFreeze check Object.isFrozen(child) before recursing, and why does it cast through unknown at the end?
Show answer
The isFrozen check stops infinite recursion on cyclic objects and avoids repeated work on shared children. The cast through unknown is needed because Object.freeze returns Readonly<T>, and TypeScript cannot show that this equals DeepReadonly<T> for a generic T. The recursive loop is what makes the claim true at runtime.