Advertisement
Advanced TypeScript, Readonly, const Assertions & Immutability

How would you implement a 'DeepReadonly<T>' utility type, and why doesn't the built-in 'Readonly<T>' recurse into nested objects?

Short answer

The built-in Readonly is a simple, SHALLOW mapped type (`{ readonly [K in keyof T]: T[K] }`) that only adds the modifier at the top level; a true deep version requires a recursive conditional type that checks whether each property's value is itself an object and, if so…

Save TypeScript mock interview
Advertisement
AModel answer
The built-in Readonly<T> is a simple, SHALLOW mapped type (`{ readonly [K in keyof T]: T[K] }`) that only adds the modifier at the top level; a true deep version requires a recursive conditional type that checks whether each property's value is itself an object and, if so, recursively applies DeepReadonly to it as well.
type DeepReadonly<T> = T extends (infer U)[]
  ? readonly DeepReadonly<U>[]
  : T extends object
    ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
    : T;

interface Config { server: { port: number } }
type Frozen = DeepReadonly<Config>; // server AND server.port are both readonly
Real-world example
Typing an immutable, deeply-nested global state tree or configuration object used throughout an application.
Likely follow-ups
  • Why might a naive DeepReadonly implementation behave incorrectly on special object types like Map, Set, or Date?
Related topics