Type-Safe Event Map Transformations
What you'll learn: How to transform event name-to-payload mappings into event name-to-handler mappings using mapped types with key remapping.
The Core Idea
Many event systems define events as a mapping from event names to payload types. But what you often need is a corresponding mapping from those same event names to handler functions that accept those payloads. Mapped types with key remapping let you build this transformation automatically and type-safely.
Think of it like this: you have a menu listing dishes and their ingredients (events and payloads). You want to automatically generate a staff roster showing which cooks handle which dishes based on those ingredients (handlers based on payloads). The transformation keeps everything synchronized.
How It Works
Start with an event map defining events and their data:
type EventMap = {
click: { x: number; y: number };
submit: { formData: string };
load: void;
};
Transform it into a handler map where each key becomes a handler function:
type EventHandlers<T> = {
[K in keyof T as `on${Capitalize<K & string>}`]: (payload: T[K]) => void;
};
type Handlers = EventHandlers<EventMap>;
// Result:
// {
// onClick: (payload: { x: number; y: number }) => void;
// onSubmit: (payload: { formData: string }) => void;
// onLoad: (payload: void) => void;
// }
The as clause remaps "click" to "onClick", while T[K] ensures each handler accepts the correct payload type. This guarantees your handler signatures stay synchronized with your event definitions.
Key Takeaway: Mapped types with key remapping can transform event-to-payload maps into event-to-handler maps, creating type-safe handler definitions that automatically stay synchronized with your event types.