Distributive Behavior in Mapped Types
What you'll learn: How mapped types automatically distribute over union types, processing each union member independently.
The Core Idea
When you apply a mapped type to a union type, TypeScript doesn't treat the union as a single blob. Instead, it distributes the mapping operation over each member of the union individually, then recombines the results back into a union.
Think of it like a factory assembly line: if you send a batch of different items (a union) through a processing machine (a mapped type), each item type gets processed separately, then they're all packaged together at the end.
How It Works
type Stringify<T> = {
[K in keyof T]: string
};
type A = { a: number };
type B = { b: boolean };
// Union input
type AorB = A | B;
// Mapped type distributes!
type StringifiedUnion = Stringify<AorB>;
// Result: Stringify<A> | Stringify<B>
// Which is: { a: string } | { b: string }
When you write Stringify<A | B>, TypeScript doesn't create one object with all properties from both A and B. Instead, it:
- Applies
StringifytoA→{ a: string } - Applies
StringifytoB→{ b: string } - Unions the results →
{ a: string } | { b: string }
This preserves the distinct shapes in your union rather than merging them into a single object type, which is exactly what you want for type safety.
Key Takeaway: Mapped types distribute over unions automatically, applying the transformation to each union member separately and returning a union of the transformed types.