TypeScript 7 reference · Type Operators and Keywords

TypeScript conditional types (T extends U ? X : Y) Operator

Choose between two types based on a condition, like a ternary for types. The basis of many utility types.

TypeScript 7 Since 2.8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

T extends U ? X : Y

Examples

A type-level ifTry it yourself
type IsString<T> = T extends string ? "yes" : "no";
const a: IsString<"hi"> = "yes";
const b: IsString<42> = "no";
console.log(a, b);

Output

yes no
Unwrap arrays with inferTry it yourself
type ElementOf<T> = T extends (infer E)[] ? E : T;
const x: ElementOf<number[]> = 5;
const y: ElementOf<string> = "not an array";
console.log(x, y);

Output

5 not an array

Version history

VersionChange
TypeScript 2.8Added

Was this page helpful?