Understanding Conditional Types in TypeScript
Conditional types in TypeScript provide a way to choose between two types based on a condition. They're extremely powerful when building utility types or performing type transformations.
They follow the format `A extends B ? C : D`, which evaluates to `C` if the condition is true, or `D` if false.
Basic Conditional Type Check
This example checks whether a given type `T` is assignable to `string`. If so, it returns `true`; otherwise, it returns `false`.
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<123>; // false
Using infer to Extract Types
Conditional types can be combined with the `infer` keyword to extract types inside structures. This is useful for unwrapping array or Promise types.
type Flatten<T> = T extends (infer U)[] ? U : T;
type A = Flatten<string[]>; // string
type B = Flatten<number>; // number
Conditional Logic Based on Object Shape
You can use conditional types to inspect object shapes and return different types based on their structure or specific values.
type ConditionalProps<T> = T extends { isActive: true } ? 'Enabled' : 'Disabled';
type A = ConditionalProps<{ isActive: true }>; // 'Enabled'
type B = ConditionalProps<{ isActive: false }>; // 'Disabled'
Conclusion
Conditional types help us write more flexible and reusable type logic by branching types based on conditions.
Mastering them is essential for writing powerful utility types, especially when working with generic and complex data structures.
Back