Type-Level Conditionals
Branch on types with conditional type expressions.
The Type-Level If
The type language gains branching with conditional types. The syntax T extends U ? X : Y reads: if T is assignable to U, the result is X, otherwise it is Y.
This is the type-level equivalent of an if / else expression.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"extends Means Assignable
The test is not equality. T extends U is true when a value of type T could be used where a U is expected. Literal types are assignable to their base type.
type T1 = "hello" extends string ? true : false; // true
type T2 = string extends "hello" ? true : false; // false
type T3 = 42 extends number ? true : false; // trueAll lessons in this course
- Types as a Computation Language
- Type-Level Conditionals
- Type-Level Recursion
- Distributive Conditional Types