Type-Level Conditionals and Branching
What you'll learn: How to implement if-then-else logic purely at the type level using conditional types to make decisions based on type relationships.
The Core Idea
Just as you use if-else statements in regular JavaScript code to make runtime decisions, TypeScript lets you make compile-time decisions about types themselves. Type-level conditionals use the extends keyword in a special syntax that asks: "Does type A satisfy type B? If yes, produce type X; otherwise, produce type Y."
Think of it like a traffic light for types: your code reaches a fork in the road at the type level, checks a condition, and TypeScript automatically picks the correct path—all before any code runs.
The Syntax
The fundamental pattern is:
T extends U ? X : Y
This reads as: "If type T is assignable to type U, then resolve to type X; otherwise, resolve to type Y."
Building If-Then-Else Logic
You can construct arbitrarily complex branching logic by nesting conditionals:
type CheckType<T> =
T extends string ? "It's a string" :
T extends number ? "It's a number" :
T extends boolean ? "It's a boolean" :
"It's something else";
type A = CheckType<"hello">; // "It's a string"
type B = CheckType<42>; // "It's a number"
type C = CheckType<true>; // "It's a boolean"
type D = CheckType<{}>; // "It's something else"
This creates a type-level switch statement that evaluates top-to-bottom, choosing the first matching branch.
Real-World Example: Smart Return Types
type SmartReturn<T> =
T extends Promise<any> ? "async function" :
T extends Array<any> ? "returns array" :
T extends void ? "returns nothing" :
"returns value";
type Result1 = SmartReturn<Promise<number>>; // "async function"
type Result2 = SmartReturn<string[]>; // "returns array"
type Result3 = SmartReturn<void>; // "returns nothing"
Key Takeaway: Conditional types let you implement if-then-else branching logic at the type level, enabling TypeScript to make intelligent decisions about types based on their characteristics—no runtime code needed.