Make all nested properties readonly
Quick Answer
`DeepReadonly<T>` recursively applies the `readonly` modifier to every property at every nesting level, making entire object trees immutable.
1type DeepReadonly<T> = {
2 readonly [P in keyof T]: T[P] extends object
3 ? DeepReadonly<T[P]>
4 : T[P];
5};
6
7// Usage
8interface Config {
9 api: { url: string; timeout: number };
10 features: { darkMode: boolean };
11}
12
13type ReadonlyConfig = DeepReadonly<Config>;TypeScript's built-in Readonly only makes the top-level properties read-only; nested objects remain mutable. DeepReadonly applies the readonly modifier recursively to every level, making entire object trees immutable at the type level — ideal for Redux state, configuration objects, and domain models.
Yes. Arrays extend `object`, so the recursive branch applies `DeepReadonly` to the element type as well. The resulting type will be `ReadonlyArray<DeepReadonly<Element>>`.
This free typescript code snippet for deep readonly type is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement deep readonly type quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.