What are conditional types in TypeScript

· Category: TypeScript

Short answer

Conditional types take the form T extends U ? X : Y and resolve to X if T is assignable to U, otherwise Y.

How it works

They enable type-level logic similar to ternary operators. The infer keyword extracts types from within a conditional, which is essential for utility types like ReturnType. TypeScript also distributes conditional types over unions automatically.

Example

type IsString<T> = T extends string ? true : false;
type Message<T> = T extends Error ? string : never;
type Return<T> = T extends (...args: any[]) => infer R ? R : never;

Why it matters

Conditional types power many advanced patterns including type extraction, overload resolution, and schema validation libraries. They allow you to build types that react to the shape of other types.