Generating Records from Union Keys
You'll learn: How to use a union type as the key set for a mapped type, ensuring every union member becomes a required property in the resulting object type.
The Core Idea
When you have a union of literal types (like "red" | "green" | "blue"), you can use mapped type syntax to generate a complete record where every member of that union becomes a property. This ensures exhaustive coverage—you can't accidentally miss a key.
Think of it like a factory that takes a list of required ingredients (your union) and produces a storage box with a labeled compartment for each one. No ingredient gets left out.
The Syntax Pattern
type Colors = "red" | "green" | "blue";
type ColorMap = {
[K in Colors]: string;
};
// Result:
// {
// red: string;
// green: string;
// blue: string;
// }
Here, [K in Colors] iterates over each literal in the Colors union, creating a property for "red", "green", and "blue". The value type (string) is applied to all of them.
Why This Matters
This pattern guarantees type safety and completeness. If you add a new color to the union later, TypeScript will immediately flag any object that doesn't include the new property:
type Status = "pending" | "success" | "error";
type StatusHandlers = {
[S in Status]: () => void;
};
const handlers: StatusHandlers = {
pending: () => console.log("Loading..."),
success: () => console.log("Done!"),
error: () => console.log("Failed!")
// If you forget one, TypeScript errors!
};
Key Takeaway: Mapping over a union type with [K in UnionType] generates an object type with one property per union member, ensuring exhaustive, type-safe record structures.