conditional type
A type that picks one of two types depending on whether a type is assignable to another, written like a ternary expression with extends.
In more detail
It is an if statement that runs in the type checker. With infer it can pull types out of arrays, promises and functions. Many utility types, such as Exclude and ReturnType, are conditional types.
Example
type UnpackPromise<T> = T extends Promise<infer R> ? R : T;Related terms
- infer — A keyword used inside the extends part of a conditional type to capture part of a matched type in a new type variable.
- distributive conditional type — A conditional type on a bare type parameter, which is applied separately to each member of a union and the results combined.
- ternary operator — A JavaScript expression made of a condition, a question mark and two options separated by a colon, giving the first option when the condition is truthy and the second otherwise.
- utility types — Generic types built into TypeScript, such as Partial, Pick and ReturnType, that compute a new type from an existing one.
Taught in
- Function Utilities: ReturnType, Parameters And Constructor — Production TypeScript
- Conditional Types: Ternary Types And Type Inference With infer — Production TypeScript
- Mapped Types, Key Remapping With as And Template Literals — Production TypeScript
- The Spine Artifact: Generating Typed Models From OpenAPI — Production TypeScript