Browse topics

TypeScript conditional types

Version
es2025
Since
2.8
Review
Draft

Summary#

A conditional type chooses a type based on assignability. Use infer in the checked pattern to capture a type for use in the true branch.

Syntax#

ts
type Choose<T> = T extends Pattern ? Match : Fallback;
type PayloadOf<T> = T extends { payload: infer P } ? P : never;

Example#

ts
type AuditEvent =
  | { kind: "login"; payload: { userId: string } }
  | { kind: "heartbeat" };

type PayloadOf<T> = T extends { payload: infer P } ? P : never;

const payload: PayloadOf<AuditEvent> = { userId: "u42" };
console.log(payload.userId);

Expected output#

Text
u42

PayloadOf keeps the login event's payload type. The heartbeat branch evaluates to never and drops out of the union.

Common mistakes#

T extends Pattern tests each union member separately when T is a bare type parameter. Write [T] extends [Pattern] to test the union as a whole. These type operations are erased from the emitted JavaScript.

Version applicability#

TypeScript 2.8 introduced conditional types, including infer and distribution over unions. All forms shown and the complete example work from that release.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0