Generics with Conditional Types
TS · Genericssyntax
type Name<T> = T extends Condition ? TrueType : FalseType;example
type IsArray<T> = T extends any[] ? true : false;
type Test1 = IsArray<string[]>; // true
type Test2 = IsArray<number>; // false
// Extracting element types
type ElementOf<T> = T extends (infer E)[] ? E : never;
type StrEl = ElementOf<string[]>; // string
type NumEl = ElementOf<number[]>; // number
type NoEl = ElementOf<boolean>; // neveroutput
// Conditional types act like type-level if/elseNote When a conditional type receives a union as T, it distributes — the condition is applied to each union member independently. To prevent distribution, wrap both sides in brackets: [T] extends [Condition].