0Pricing
TypeScript Academy · Lesson

Deep Immutability Patterns

Achieve deeply readonly structures with recursive types.

Shallow vs Deep Immutability

The readonly modifier is shallow: it protects the top level but not nested objects. Deep immutability means every level, all the way down, is readonly. Achieving it takes extra work.

interface State { readonly user: { name: string }; }
const s: State = { user: { name: 'Ada' } };
// s.user = {...}; // Error (shallow protection)
s.user.name = 'Grace'; // allowed! nested field is mutable
console.log(s.user.name);

Why Shallow Isn't Enough

For state management and shared data, shallow readonly leaves nested fields exposed. A single overlooked mutation deep in a structure can cause subtle, hard-to-trace bugs.

interface Config { readonly db: { host: string; port: number }; }
const c: Config = { db: { host: 'localhost', port: 5432 } };
c.db.port = 9999; // mutates nested data despite readonly
console.log(c.db.port);

All lessons in this course

  1. readonly Properties
  2. readonly Arrays and Tuples
  3. ReadonlyArray and ReadonlyMap
  4. Deep Immutability Patterns
← Back to TypeScript Academy