To create a deep readonly type in TypeScript, you can use recursion combined with the built-in Readonly
type. This involves creating a custom recursive type that checks if a given type is an object and, if so, applies Readonly
to all its properties, including nested objects.
Example:
type DeepReadonly<T> = T extends Function ? T : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T; interface User { name: string; details: { age: number; address: string; }; } const user: DeepReadonly<User> = { name: 'John', details: { age: 30, address: '123 Street' } }; user.details.age = 31; // Error, 'age' is readonly user.name = 'Alice'; // Error, 'name' is readonly
The DeepReadonly<T>
type recursively applies readonly
to all properties of an object, including those that are nested, ensuring the entire object is read-only.