Course contentsShow
← TypeScript
Lesson 738 of 1,79617. Mapped TypesFree lesson

Preserving vs Transforming Union Members

When to keep union members as-is versus transforming them during mapping operations.

Preserving vs Transforming Union Members

What you'll learn: How to decide whether to keep union type members unchanged or transform them during mapped type operations.

When working with mapped types, you'll often encounter unions as input. The key choice you face is whether your mapped type should preserve each union member as-is (maintaining the union structure) or transform them into something new.

The Core Decision

Think of union members like ingredients in a recipe. Sometimes you want to keep each ingredient separate and identifiable (preserving), and sometimes you want to blend them together into a completely new form (transforming).

Preserving means distributing your mapping operation across each union member individually, maintaining the union shape in the output.

Transforming means treating the entire union as a single entity and applying an operation that collapses or changes the overall structure.

When to Preserve

Preserve union members when you need to maintain distinct type branches:

type Status = "idle" | "loading" | "success";

// Preserving: each member stays distinct
type StatusHandlers = {
  [K in Status]: () => void;
};
// Result: { idle: () => void; loading: () => void; success: () => void }

When to Transform

Transform when you want to unify or collapse the union:

type Mixed = string | number;

// Transforming: treating as one unified type
type Container<T> = {
  value: T;
  reset: () => void;
};

type MixedContainer = Container<Mixed>;
// Result: { value: string | number; reset: () => void }

The difference lies in where the union appears in your result: preserved mappings distribute it across properties, while transforming mappings keep it unified within property types.

Key Takeaway: Preserve union members when you need distinct handling per variant; transform them when you need unified behavior across all variants.