Union Types as Mapped Type Input
What You'll Learn
You'll learn how union types become the keys of an object when used as input to a mapped type, automatically creating multiple properties from a single union.
The Core Idea
When you pass a union type into a mapped type, TypeScript iterates over each member of the union and creates a separate property for each one. This turns a union like "apple" | "banana" | "cherry" into an object type with three properties: apple, banana, and cherry.
Think of it like a vending machine that takes a list of snack names and automatically creates a slot for each snack. You give it the list once, and it builds all the compartments.
How It Works
type Fruit = "apple" | "banana" | "cherry";
type FruitInventory = {
[K in Fruit]: number;
};
// Result:
// {
// apple: number;
// banana: number;
// cherry: number;
// }
The union Fruit has three string literal members. When used in the mapped type with [K in Fruit], TypeScript creates three properties—one for each union member.
Practical Example
type Status = "idle" | "loading" | "success" | "error";
type StatusMessages = {
[S in Status]: string;
};
const messages: StatusMessages = {
idle: "Waiting to start",
loading: "Fetching data...",
success: "Done!",
error: "Something went wrong"
};
This pattern ensures you provide a message for every possible status value. If you add a new status to the union, TypeScript will immediately require a corresponding property.
Key Takeaway: Union types become object property keys when used in mapped types, transforming a list of values into a structured object type with matching properties.