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
Syntax
T extends U ? X : Y
Examples
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
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
| Version | Change |
|---|---|
| TypeScript 2.8 | Added |
Related
infer· Inside a conditional type, infer captures part of a type into a new type variable, e.g. the element type of an array.Exclude<UnionType, ExcludedMembers>· Remove members from a union type. Exclude<'a' | 'b' | 'c', 'a'> is 'b' | 'c'.mapped types ({ [K in Keys]: … })· Create a new object type by transforming every property of another, the way Partial and Readonly are built.- TypeScript keyof, typeof and Indexed Access · tutorial