Practical Union Mapping Patterns
What you'll learn: How to apply mapped types to unions in real-world scenarios like event systems, action creators, and discriminated union utilities.
Now that you've seen how mapped types interact with unions, let's look at patterns you'll actually use in production code.
Event Type Maps
Imagine building a type-safe event system where each event name maps to its payload type:
type Events = {
login: { userId: string; timestamp: number };
logout: { userId: string };
error: { message: string; code: number };
};
// Map event names to handler functions
type EventHandlers = {
[K in keyof Events]: (payload: Events[K]) => void;
};
// Now you get perfect type safety:
const handlers: EventHandlers = {
login: (payload) => console.log(payload.userId), // ✓
logout: (payload) => console.log(payload.userId), // ✓
error: (payload) => console.log(payload.code), // ✓
};
Action Creator Pattern
Redux-style action creators benefit hugely from mapped types:
type Actions = {
INCREMENT: { by: number };
DECREMENT: { by: number };
RESET: undefined;
};
type ActionCreators = {
[K in keyof Actions]: (payload: Actions[K]) => { type: K; payload: Actions[K] };
};
This pattern generates type-safe action creators automatically from your action definitions.
Discriminated Union Utilities
Extract specific variants from discriminated unions:
type Result =
| { status: "success"; data: string }
| { status: "error"; message: string }
| { status: "loading" };
type ByStatus<Status extends Result["status"]> = Extract<Result, { status: Status }>;
// ByStatus<"success"> = { status: "success"; data: string }
Key Takeaway: Mapped types over unions shine in event systems, state management, and any pattern where you need to generate related types from a single source of truth—reducing duplication and keeping types synchronized.