Course contentsShow
← TypeScript
Lesson 674 of 1,79616. Utility TypesFree lesson

Deep vs Shallow Transformations

Built-in utilities only transform top-level properties; creating recursive versions requires custom mapped types.

Deep vs Shallow Transformations

What you'll learn: Why TypeScript's built-in utilities like Partial, Required, and Readonly only transform the outermost layer of your types, and what that means for nested objects.


The Surface-Level Truth

All the utility types you've seen so far — Partial<T>, Required<T>, and Readonly<T> — operate only on top-level properties. They don't recursively transform nested objects.

Think of it like painting a house: these utilities only paint the exterior walls, not the interior rooms.

interface User {
  name: string;
  address: {
    street: string;
    city: string;
  };
}

type PartialUser = Partial<User>;
// Result:
// {
//   name?: string;
//   address?: { street: string; city: string }; // address itself is optional
// }

// BUT: if address exists, street and city are STILL required!
const user: PartialUser = {
  address: {} // ❌ Error: street and city are missing
};

Why This Happens

Built-in utilities use mapped types that iterate over the immediate keys of T. They transform each property in place, but don't recurse into nested object structures.

The Solution: Custom Recursive Types

To create a deep transformation, you need to write custom mapped types that conditionally apply themselves recursively:

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

type DeepPartialUser = DeepPartial<User>;
// Now address.street and address.city are ALSO optional

This pattern checks if each property is an object and, if so, applies DeepPartial again.


Key Takeaway: TypeScript's built-in utilities (Partial, Required, Readonly) are shallow — they only transform top-level properties. For deep transformations on nested objects, you must create custom recursive mapped types using conditional logic.