Sub topic 12
Going deeper: a recursive `DeepReadonly` type
This chapter assumes basic TypeScript syntax, interfaces, type aliases, union types, and JavaScript objects and arrays. You should also know that TypeScript checks types at compile time, while JavaScript runs at runtime.
Why `Readonly<T>` is not enough
TypeScript’s built-in Readonly<T> protects only the properties directly declared on a type. It is shallow. If a readonly property contains another object or an array, the nested value can still be changed.
interface AppConfig {
readonly server: {
host: string;
ports: number[];
};
}
const config: Readonly<AppConfig> = {
server: {
host: "localhost",
ports: [3000]
}
};
// config.server = { host: "example.com", ports: [80] }; // Error
config.server.host = "example.com"; // Allowed
config.server.ports.push(8080); // AllowedThe server property cannot be replaced, but the object stored in server remains mutable. A recursive DeepReadonly<T> type applies readonly to nested objects and arrays as well.
Defining `DeepReadonly<T>`
A conditional type chooses a result based on the kind of type it receives:
type DeepReadonly<T> =
T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;This definition has three cases:
- Functions are returned unchanged. Making a function’s internal behavior readonly is not the purpose of this type.
- Objects are converted with a mapped type. Each property becomes readonly, and
DeepReadonlyis applied to its property type. - Primitive values such as strings, numbers, booleans,
null, andundefinedare returned unchanged.
The recursion stops naturally when it reaches a primitive or a function.
interface Settings {
ui: {
theme: string;
tags: string[];
};
retryCount: number;
format(): string;
}
const settings: DeepReadonly<Settings> = {
ui: {
theme: "dark",
tags: ["compact", "high-contrast"]
},
retryCount: 3,
format() {
return this.ui.theme;
}
};
// settings.ui.theme = "light"; // Error
// settings.ui.tags.push("large"); // Error
// settings.retryCount = 4; // Error
console.log(settings.format()); // Functions remain callableWhen TypeScript applies the mapped type to string[], the array becomes readonly. Its mutating methods, such as push, are no longer available.
Arrays, tuples, and special cases
The basic recursive definition also handles nested arrays and tuples. A tuple keeps its positions and literal element types while making the tuple readonly.
type Data = {
coordinates: [number, number];
labels: string[];
};
const data: DeepReadonly<Data> = {
coordinates: [10, 20],
labels: ["north", "east"]
};
// data.coordinates[0] = 5; // Error
// data.coordinates.push(30); // Error
// data.labels.push("south"); // Error
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
console.log(total(data.coordinates));A readonly type is useful at an API boundary. It lets a function promise that it will inspect data without changing it.
A practical mental model
Think of DeepReadonly<T> as repeatedly applying this rule:
- If the value is a function, leave it alone.
- If the value is an object or array, make each accessible property readonly.
- For each property, repeat the rule.
- If the value is primitive, stop.
Limits and design choices
Recursive types need deliberate boundaries. A type containing a Date, Map, Set, or class instance is an object, so the simple definition recursively transforms its members. That may not match the intended public API.
You can add special cases when necessary:
type DeepReadonlySafe<T> =
T extends (...args: any[]) => any ? T :
T extends Date ? T :
T extends object ? { readonly [K in keyof T]: DeepReadonlySafe<T[K]> } :
T;This version leaves Date unchanged while still protecting ordinary nested objects. Whether a special type should remain unchanged depends on how your application uses it.
Exercise
In the Settings example, why does DeepReadonly<Settings> prevent settings.ui.tags.push("large") even though tags is nested?
Show answer
The mapped type recursively applies DeepReadonly to ui, then to tags. The array becomes readonly, so its mutating push method is unavailable.