Distributive conditional types let you apply a condition to each item in a group separately. This helps you create flexible types that change based on each item.
0
0
Distributive conditional types in Typescript
Introduction
When you want to transform each type in a list differently based on a condition.
When you need to filter types inside a union to keep only some parts.
When you want to map over a union type and change each member.
When you want to create types that adapt automatically to different inputs.
Syntax
Typescript
T extends U ? X : YIf T is a union type, TypeScript applies the condition to each member separately.
This is called distributive behavior and happens only if T is a naked type parameter on the left side of extends.
Examples
The condition runs on
string and number separately, so the result is a union of both outcomes.Typescript
type Result<T> = T extends string ? "yes" : "no"; type Test = Result<string | number>; // Test is "yes" | "no"
Wrapping
T in a tuple disables distribution, so the whole union is checked at once.Typescript
type NotDistributive<T> = [T] extends [string] ? "yes" : "no"; type Test = NotDistributive<string | number>; // Test is "no"
Sample Program
This program creates a type that keeps only string types from a union. It shows how distributive conditional types filter out non-string types.
Typescript
type FilterStrings<T> = T extends string ? T : never; type Mixed = string | number | boolean; type OnlyStrings = FilterStrings<Mixed>; // Test with a variable const example1: OnlyStrings = "hello"; // const example2: OnlyStrings = 123; // Error: number not assignable to string console.log(example1);
OutputSuccess
Important Notes
Distributive conditional types only work when the checked type is a plain type parameter, not wrapped in another type like a tuple.
They are very useful for creating flexible and reusable type utilities.
Summary
Distributive conditional types apply conditions to each member of a union separately.
They help filter, map, or transform union types easily.
Wrapping the type parameter disables distribution.