What are Conditional Types?
Conditional types allow you to create types that depend on a condition. They follow the syntax:
SomeType extends OtherType ? TrueType : FalseType.This is essentially an "if-statement" for your types, allowing for incredibly flexible and dynamic APIs.
1. Basic Usage
A common use case is creating a type that returns different types based on the input.
typescript
2. Distributive Conditional Types
When conditional types act on a generic type that is a union, they "distribute" across that union.
typescript
3. The infer Keyword
The
infer keyword allows you to extract types from within other types. It can only be used in the extends clause of a conditional type.Example: Getting the Return Type of a Function
typescript
Example: Extracting the Type of an Array Element
typescript
4. Real-World Use Case: API Responses
Conditional types are perfect for handling complex API responses where the shape depends on a status or input.
typescript
Summary Checklist
- Syntax:
T extends U ? X : Y. - Use
inferto extract sub-types dynamically. - Understand distribution across unions.
- Perfect for reducing boilerplate in generic logic.
- Enables "Type-level programming" in TypeScript.