5 min read
•Question 18 of 48hardWhat are Conditional Types in TypeScript?
Types that depend on conditions.
What You'll Learn
- Conditional type syntax
- Type inference with infer
- Common patterns
Conditional Types
code.tsTypeScript
// Syntax: T extends U ? X : Y
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // falsePractical Examples
code.tsTypeScript
// Extract array element type
type ElementType<T> = T extends (infer U)[] ? U : never;
type NumArr = ElementType<number[]>; // number
type StrArr = ElementType<string[]>; // string
// Extract function return type
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Fn = () => string;
type Result = ReturnType<Fn>; // stringDistributive Conditional Types
code.tsTypeScript
type ToArray<T> = T extends any ? T[] : never;
type StrOrNum = ToArray<string | number>;
// string[] | number[]Exclude and Extract
code.tsTypeScript
// Built-in utility types using conditional types
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"