27. How can you create a deep readonly type using TypeScript?

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.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.