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

Type-Level If-Else Chains

Build nested conditionals that mimic if-else-if logic for sophisticated type transformations.

Type-Level If-Else Chains

What You'll Learn

You'll learn how to chain multiple conditional types together to create sophisticated type transformations that mimic multi-branch if-else logic at the type level.


The Core Idea

Just like JavaScript's if-else-if-else chains let you test multiple conditions in sequence, TypeScript conditional types can be nested to handle complex branching scenarios. Each conditional type can contain another conditional type in its "true" or "false" branch, creating a cascade of type-level decisions.

Think of it like a restaurant menu categorization system: "If it's meat, classify as 'Protein'. Else if it's lettuce, classify as 'Vegetable'. Else if it's bread, classify as 'Grain'. Else classify as 'Other'." Each condition is checked in order until one matches.


Building If-Else-If Chains

The pattern looks like this:

type Categorize<T> =
  T extends string ? 'text' :
  T extends number ? 'numeric' :
  T extends boolean ? 'flag' :
  'unknown';

type A = Categorize<'hello'>;      // 'text'
type B = Categorize<42>;           // 'numeric'
type C = Categorize<true>;         // 'flag'
type D = Categorize<null>;         // 'unknown'

Each ? starts a new branch, and the : before the next condition acts like "else if". The final : provides the default "else" case.


Real-World Pattern: Response Type Transformation

type Status = 'success' | 'error' | 'pending' | 'idle';

type StatusMessage<S extends Status> =
  S extends 'success' ? { message: string; data: unknown } :
  S extends 'error' ? { message: string; error: Error } :
  S extends 'pending' ? { message: string } :
  { message: never };

This cascades through each status type, returning progressively different shapes based on which condition matches first.


Key Takeaway: Nested conditional types let you build multi-branch type-level logic by chaining conditions with the ternary operator, creating powerful type transformations that handle complex scenarios gracefully.