Course contentsShow
← TypeScript
Lesson 813 of 1,79618. Conditional TypesFree lesson

The DeepReadonly Pattern

Make all properties at all nesting levels readonly by recursively applying readonly with conditional type checks.

The DeepReadonly Pattern

What you'll learn: How to make every property in an object — at every nesting level — immutable using a recursive conditional type.


The Problem with Shallow Readonly

You already know the Readonly<T> utility makes all top-level properties readonly. But it doesn't touch nested objects:

type User = {
  name: string;
  address: {
    city: string;
  };
};

type ReadonlyUser = Readonly<User>;

const user: ReadonlyUser = {
  name: "Alice",
  address: { city: "Boston" }
};

// ❌ Error: cannot reassign top-level property
user.name = "Bob";

// ✅ But this compiles! Nested properties aren't readonly
user.address.city = "New York";

Building DeepReadonly

To protect nested objects, we need a recursive conditional type that applies readonly at every level:

type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? DeepReadonly<T[K]>
    : T[K];
};

How it works:

  1. Map over every key K in T
  2. Add the readonly modifier
  3. Conditional check: Is the property's type an object?
    • Yes: Recursively apply DeepReadonly to that nested object
    • No: Keep the primitive type as-is

Seeing It in Action

type DeepReadonlyUser = DeepReadonly<User>;

const user: DeepReadonlyUser = {
  name: "Alice",
  address: { city: "Boston" }
};

// ❌ Error: top-level readonly
user.name = "Bob";

// ❌ Error: nested property also readonly!
user.address.city = "New York";

// ❌ Error: can't reassign nested object
user.address = { city: "Chicago" };

Now everything is immutable, no matter how deeply nested.


When to Use DeepReadonly

  • Immutable configuration objects that shouldn't change after initialization
  • State snapshots where you want compile-time guarantees nothing mutates
  • Defensive library APIs that return deeply frozen data structures

Trade-off: The recursion works at compile time only — JavaScript objects remain mutable at runtime unless you also use Object.freeze() recursively.


Key Takeaway:
DeepReadonly<T> uses a conditional type to recursively apply readonly to all properties at all nesting levels, protecting entire object trees from mutation at the type level.