Advanced Types and Real-World PatternsLesson 6.2
Conditional types in TypeScript ternary logic at the type level
conditional type syntax, extends in conditional types, infer keyword, distributive conditional types, NonNullable explained
Conditional type syntax
type IsString = T extends string ? true : false;
type A = IsString; // true
type B = IsString; // falseDistributive conditional types
When T is a union, conditional types distribute over each member:
type Flatten = T extends Array ? Item : T;
type A = Flatten; // string
type B = Flatten; // number (no change)
type C = Flatten<(string|number)[]>; // string | numberinfer keyword
infer captures a type inside a conditional check:
type UnpackPromise = T extends Promise ? R : T;
type A = UnpackPromise>; // string
type B = UnpackPromise; // numberThis is how the built-in Awaited and ReturnType are implemented. The infer variable only exists within the conditional branch where it was matched.
