Conditional Types
Conditional types select a type based on a condition, using the syntax T extends U ? X : Y.
Basic example
ts
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // falseWith infer
infer lets you extract and capture a type from within a conditional.
ts
// extract the return type manually (like ReturnType<T>)
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function greet(): string { return 'hello'; }
type Result = MyReturnType<typeof greet>; // stringDistributive conditional types
When T is a union, the condition is applied to each member.
ts
type NonNullable<T> = T extends null | undefined ? never : T;
type A = NonNullable<string | null | undefined>; // stringPractical example
ts
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type Str = Flatten<string[]>; // string
type Num = Flatten<number>; // numberConditional types are the basis for many built-in utility types:
NonNullable,ReturnType,Parameters,Awaited.
updated
did you know it?