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

Building a Deep Readonly with infer

Using infer recursively to traverse object and array types, applying readonly modifiers at every level.

Building a Deep Readonly with infer

You'll learn: How to use infer recursively to create a type that makes every property—including nested objects and array elements—readonly at all levels.

The Problem with Shallow Readonly

The built-in Readonly<T> utility only makes the top-level properties readonly. If your object contains nested objects or arrays, those inner values remain mutable:

type Shallow = Readonly<{ user: { name: string } }>;
// user property is readonly, but user.name is still mutable!

To achieve true immutability at the type level, you need a deep readonly type that traverses the entire structure.

Recursive Traversal with infer

The key insight: use conditional types with infer to pattern-match on the structure, then recursively apply readonly transformations:

type DeepReadonly<T> = T extends object
  ? T extends (...args: any[]) => any
    ? T // Don't transform functions
    : { readonly [K in keyof T]: DeepReadonly<T[K]> }
  : T;

How it works:

  1. Check if T is an object — if not (primitive), return as-is
  2. Skip functions — preserve callable types unchanged
  3. Map over properties — make each property readonly
  4. Recurse on property types — DeepReadonly<T[K]> handles nesting

Handling Arrays with infer

Arrays need special treatment. Extract the element type, make it deeply readonly, then reconstruct:

type DeepReadonly<T> = 
  T extends (infer U)[]
    ? readonly DeepReadonly<U>[]
    : T extends object
      ? T extends (...args: any[]) => any
        ? T
        : { readonly [K in keyof T]: DeepReadonly<T[K]> }
      : T;

Here, infer U captures the array element type, then we recursively apply DeepReadonly<U> and wrap in a readonly array.

Putting It All Together

type DeepReadonly<T> = 
  T extends (infer U)[]
    ? readonly DeepReadonly<U>[]
    : T extends object
      ? T extends (...args: any[]) => any
        ? T
        : { readonly [K in keyof T]: DeepReadonly<T[K]> }
      : T;

type Config = {
  db: {
    host: string;
    ports: number[];
  };
};

type Frozen = DeepReadonly<Config>;
// All properties readonly: db, host, and the ports array + elements

The recursion continues until hitting primitives, creating a fully immutable type structure.

Key Takeaway: By combining infer with recursive conditional types, you can traverse arbitrarily nested objects and arrays, applying readonly modifiers at every level to create a truly immutable type representation.