Skip to content
typescript questions

TypeScript · 5 of 10senior~1 min

What are conditional types and how do they work?

#types#advanced

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>; // false

With 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>; // string

Distributive 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>; // string

Practical example

ts
type Flatten<T> = T extends Array<infer Item> ? Item : T; type Str = Flatten<string[]>; // string type Num = Flatten<number>; // number

Conditional types are the basis for many built-in utility types: NonNullable, ReturnType, Parameters, Awaited.

updated

did you know it?

related questions