Glossary / Conditional types
Conditional types
Conditional types select a type based on assignability, using the form T extends U ? X : Y. They let libraries express type-level transformations that depend on input shapes, such as extracting a function's return type or filtering union members, but complex conditional types can become difficult to infer and explain.
Evaluation and distributivity
type IsString<T> = T extends string ? true : false;
type A = IsString<'x'>; // true
When the checked type is a naked type parameter, a conditional distributes over unions: ToArray<string | number> can become ToArray<string> | ToArray<number>. Wrapping the checked side, such as [T] extends [U], suppresses distribution and checks the union as a whole. infer introduces a type variable inside a conditional pattern, commonly to extract a nested type.
Conditional types may remain deferred when generic parameters are unknown, so a displayed declaration can look more complex than a concrete instantiation. never interacts with distributive conditionals as an empty union, often yielding never unexpectedly.
Engineering guidance
Use named helper aliases and small transformations. Test representative, union, never, any, and unknown inputs; any can produce surprising branches. Prefer simpler overloads or explicit helper interfaces when conditional logic becomes opaque. Remember that the result is compile-time only and does not branch or validate at runtime.
Interview questions
- What does a conditional type express? A type-level choice based on assignability.
- When does distribution occur? When the checked side is a naked type parameter and it is instantiated with a union.
- How suppress distribution? Wrap the checked type, often in a tuple.
- What is
inferfor? Capturing a type matched inside a conditional pattern. - Why test
never? Distributed conditionals over the empty union commonly yieldnever.