Conditional types select types based on conditions using the syntax T extends U ? X : Y. They enable type-level programming, allowing different types based on input. Combined with infer, they can extract and transform types dynamically.
Conditional Type Syntax:
T extends U ? X : YThe 'infer' Keyword:
Use Cases:
// Simple conditional type
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
type C = IsString<'hello'>; // true (literal extends string)
// Conditional with multiple checks
type TypeName<T> =
T extends string ? 'string' :
T extends number ? 'number' :
T extends boolean ? 'boolean' :
T extends undefined ? 'undefined' :
T extends Function ? 'function' :
'object';
type T1 = TypeName<string>; // 'string'
type T2 = TypeName<() => void>; // 'function'
type T3 = TypeName<string[]>; // 'object'
// Distributive behavior with unions
type Stringify<T> = T extends any ? `${T & string}` : never;
type Result = Stringify<'a' | 'b' | 'c'>;
// 'a' | 'b' | 'c' - distributed over each member