Advertisement
Advanced TypeScript, Mapped Types

How would you implement a deep 'DeepReadonly<T>' mapped type that recursively makes every nested property readonly?

Short answer

Combine a mapped type with a conditional type: for each key, check if its value is itself an object (and not a function or array edge case you want to treat specially); if so, recurse DeepReadonly into it, otherwise leave the primitive value type as-is — applied alongside the…

Save TypeScript mock interview
Advertisement
AModel answer
Combine a mapped type with a conditional type: for each key, check if its value is itself an object (and not a function or array edge case you want to treat specially); if so, recurse DeepReadonly into it, otherwise leave the primitive value type as-is — applied alongside the readonly modifier at every level.
type DeepReadonly<T> = T extends object
  ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
  : T;

interface Config { server: { host: string; port: number }; }
type FrozenConfig = DeepReadonly<Config>;
// server itself and server.host/server.port are all readonly
Real-world example
Typing a fully immutable application state tree or configuration object, preventing accidental deep mutation anywhere.
Likely follow-ups
  • Why does this DeepReadonly implementation need special handling to correctly deal with array or Map/Set properties?
Related topics