Conditional Types with Union Input
What You'll Learn
You'll discover how TypeScript automatically distributes conditional types over each member of a union, transforming them individually rather than treating the union as a whole.
The Distribution Behavior
When you apply a conditional type to a union type, TypeScript does something powerful: it distributes the conditional check across each member of the union separately, then reunites the results back into a union.
Think of it like sorting mail for multiple addresses. If you have letters going to three different houses, you apply the same routing rule to each address individually, then collect all the results together.
The Pattern
type OnlyStrings<T> = T extends string ? T : never;
// Input: a union type
type MixedUnion = string | number | boolean;
// TypeScript processes it like this internally:
// (string extends string ? string : never) |
// (number extends string ? number : never) |
// (boolean extends string ? boolean : never)
type Result = OnlyStrings<MixedUnion>;
// Result = string | never | never
// Which simplifies to: string
Each union member gets its own conditional check. The final type is the union of all the results.
Filtering Unions
This distribution behavior makes conditional types perfect for filtering union types:
type ExtractNumbers<T> = T extends number ? T : never;
type Mixed = 1 | "hello" | 2 | false | 3;
type JustNumbers = ExtractNumbers<Mixed>;
// JustNumbers = 1 | 2 | 3
The never results get dropped from the final union, leaving only the matching members.
Why This Matters
This automatic distribution is what makes utility types like Exclude and Extract work. Without it, conditional types would treat string | number as a single unit instead of checking string and number separately.
Key Takeaway: Conditional types automatically distribute over union type inputs, applying the condition to each union member individually and combining the results, enabling powerful type filtering and transformation patterns.