TypeScript Master (50 Qs)•Part 2: Advanced Type System & Metaprogramming (Mid-Level)
What are Conditional Types and Distributive Conditional Types?
junior LevelCode ExampletypescriptAdvanced Type System
In Simple Words:
Conditional types choose one of two possible types based on a subtyping relationship:
T extends U ? X : Y
Distributive Behavior:
When a conditional type operates on a generic union type (a "naked" type parameter), it automatically distributes over each union member:
typescript
type ToArray<T> = T extends any ? T[] : never;
type Result = ToArray<string | number>;
// Distributes as: ToArray<string> | ToArray<number>
// Evaluates to: string[] | number[]