Real-World Pattern: Type-Safe Event Handlers
What You'll Learn
You'll learn how to use conditional constraints to ensure event handler functions accept only the correct payload type for each specific event name.
The Problem
In event-driven systems (like DOM events, custom event emitters, or message buses), you often have multiple event types, each with its own payload structure. Without proper typing, you might pass the wrong handler to the wrong event, leading to runtime errors.
The Solution: Conditional Constraints
By combining conditional types with extends constraints and keyof, you can create a type-safe event system where the handler's parameter type automatically matches the event name.
Here's the pattern:
type EventMap = {
"user:login": { userId: string; timestamp: number };
"user:logout": { userId: string };
"post:created": { postId: string; title: string };
};
function on<K extends keyof EventMap>(
eventName: K,
handler: (payload: EventMap[K]) => void
): void {
// Implementation...
}
// ✅ Correct: handler type matches event
on("user:login", (data) => {
console.log(data.userId, data.timestamp); // TypeScript knows the shape!
});
// ❌ Error: 'timestamp' doesn't exist on logout payload
on("user:logout", (data) => {
console.log(data.timestamp); // Type error caught!
});
The constraint K extends keyof EventMap ensures K is a valid event name, while EventMap[K] performs a lookup type to retrieve the exact payload type for that event.
Key Takeaway: Conditional constraints with keyof and lookup types create type-safe event systems where handlers are automatically matched to their corresponding event payloads, catching mismatches at compile time.