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

Conditional Types Within Union Mappings

Combining conditional type logic with union mapping to transform different members differently.

Conditional Types Within Union Mappings

What you'll learn: How to use conditional type logic inside mapped types to transform different union members in different ways based on their characteristics.


Understanding the Concept

You've learned how to iterate over union types with mapped types, and you know how conditional types can branch logic based on type properties. Now you can combine both techniques to apply different transformations to different members of a union.

Think of it like a factory assembly line with smart sorting: as each item (union member) comes through, the machinery checks what type of item it is and applies a specific transformation just for that type. A mapped type provides the iteration, while a conditional type provides the branching logic.


How It Works

When you map over a union type, each member is processed individually. By embedding a conditional type check in the mapped property value, you can ask questions like "Is this member a string?" or "Does this type extend a certain shape?" and return different types accordingly.

The pattern:

type SmartTransform<T> = {
  [K in keyof T]: T[K] extends string ? string[] : T[K]
}

Here, for each property K, we check: "Is the property's type a string?" If yes, transform it to string[]. Otherwise, keep it as-is.


Example: Differentiate by Type

type User = {
  name: string;
  age: number;
  active: boolean;
}

type Arrayify<T> = {
  [K in keyof T]: T[K] extends string ? string[] : T[K]
}

type Result = Arrayify<User>;
// { name: string[]; age: number; active: boolean }

Only the string properties became arrays—number and boolean stayed unchanged.


Key takeaway: Conditional types within mapped types let you apply targeted transformations to different union members, creating flexible, type-aware utilities that branch behavior based on each property's characteristics.