Distributing Over String Literal Unions
You'll learn how conditional types automatically apply transformations to each member of a string literal union, enabling powerful type-level string manipulation.
The Core Idea
When you pass a union of string literals into a distributive conditional type, TypeScript automatically "unwraps" the union and applies the conditional to each member individually, then re-unions the results. This lets you transform entire sets of string types programmatically.
Think of it like a factory assembly line: instead of processing a batch of items together, you automatically process each item separately and collect all the individual results at the end.
How It Works
// A distributive conditional that adds "on" prefix
type AddOn<T> = T extends string ? `on${T}` : never;
// Input: union of string literals
type Events = "click" | "hover" | "focus";
// Distribution happens automatically:
// "click" → "onclick"
// "hover" → "onhover"
// "focus" → "onfocus"
type EventHandlers = AddOn<Events>;
// Result: "onclick" | "onhover" | "onfocus"
The conditional type processes each union member separately and combines the results back into a union.
Practical String Transformations
// Filter strings matching a pattern
type StartsWithOn<T> = T extends `on${string}` ? T : never;
type Mixed = "onclick" | "value" | "onload" | "disabled";
type Filtered = StartsWithOn<Mixed>;
// Result: "onclick" | "onload"
// Transform HTTP methods to handler names
type ToHandler<T> = T extends string ? `handle${Capitalize<T>}` : never;
type Methods = "get" | "post" | "delete";
type Handlers = ToHandler<Methods>;
// Result: "handleGet" | "handlePost" | "handleDelete"
Distribution allows you to filter unwanted strings by returning never for non-matching members, which disappears from the final union.
Key Takeaway: Distributive conditionals automatically loop over each string literal in a union, letting you transform, filter, or validate entire sets of string types with type-safe, compile-time operations.