Conditional Types
A conditional type has the form T extends U ? X : Y. It selects a type based on assignability. When the checked type is a naked type parameter, conditional types distribute over unions: ToArray<string | number> becomes string[] | number[] if defined as T extends unknown ? T[] : never.
Distribution is powerful but can surprise you. Wrapping the checked type in a tuple—[T] extends [U]—checks the union as a whole rather than distributing. Use conditional types when the relationship is reusable and the result is clearer than multiple overloads.
Conditional type example
type ToArray<T> = T extends unknown ? T[] : never;
type Distributed = ToArray<string | number>;
// string[] | number[]
type WholeUnionCheck<T> = [T] extends [string] ? true : false;
type Check = WholeUnionCheck<string | number>; // false💡 The first conditional distributes because
T is naked on the left of extends. The tuple wrapper suppresses distribution and evaluates the union as one type.Key Takeaways
- Conditional types choose a type based on assignability.
- Naked type parameters distribute over unions.
- Tuple wrapping can suppress distributive behavior.
Knowledge Check
When does a conditional type distribute over a union?