TypeScript Conditional Types
Conditional types let you choose between two types based on a condition, similar to a ternary expression but evaluated at the type level. The syntax is `T extends U ? X : Y`.
Conditional types are especially powerful when combined with generics, letting a type change its shape depending on what type is passed in, enabling very flexible and precise type definitions.
type IsString<T> = T extends string ? "yes" : "no";Basic conditional types
Writing `type IsString<T> = T extends string ? "yes" : "no";` checks whether T extends (is compatible with) string, resolving to one of two literal types.
Conditional types with generics
Conditional types are often used inside generic type aliases or utility types to adapt behavior based on the actual type supplied by the caller.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>;
type B = IsString<number>;
const a: A = "yes";
const b: B = "no";
console.log(a, b);yes noA resolves to the "yes" branch and B resolves to the "no" branch based on the conditional check.
type ElementType<T> = T extends (infer U)[] ? U : T;
type Num = ElementType<number[]>;
const n: Num = 5;
console.log(n);5The conditional type uses `infer` to extract the element type out of an array type.
Key points
- Conditional types use the syntax `T extends U ? X : Y`.
- They let a type resolve differently depending on another type.
- The `infer` keyword can extract a type from within a conditional check.
- Conditional types are commonly combined with generics for flexible utilities.
