Course contentsShow
← TypeScript
Lesson 581 of 1,79614. Generics in PracticeFree lesson

Event Handlers and Callbacks

Generic event emitters and listeners that preserve event payload types.

Event Handlers and Callbacks

What You'll Learn

You'll learn how to build generic event emitters and listeners that preserve the exact type of each event's payload, giving you full type safety without repeating yourself.


The Problem with Untyped Event Systems

Event-driven code is everywhere — user clicks, server responses, message queues. But traditional event systems lose type information:

// ❌ No type safety
emitter.on('userLogin', (data) => {
  // What shape is 'data'? We don't know!
  console.log(data.userId); // Could crash
});

Every callback handler requires manual type assertions or documentation. You can't rely on IntelliSense, and refactoring becomes dangerous.


Generic Event Emitters: Type-Safe Payloads

By combining generics with a mapped event registry, you can enforce that each event name expects a specific payload type:

interface EventMap {
  userLogin: { userId: string; timestamp: Date };
  dataReceived: { bytes: number };
  error: { message: string };
}

// Generic listener that preserves payload type
function on<K extends keyof EventMap>(
  eventName: K,
  callback: (payload: EventMap[K]) => void
): void {
  // Implementation would store callback
  // TypeScript ensures callback type matches event
}

// ✅ Fully type-safe
on('userLogin', (data) => {
  console.log(data.userId);    // ✅ Known to be string
  console.log(data.timestamp); // ✅ Known to be Date
});

on('dataReceived', (data) => {
  console.log(data.bytes); // ✅ Known to be number
});

The generic K captures which event you're listening to, and EventMap[K] retrieves the exact payload shape. No guessing, no any.


Key Takeaway:
Generic event handlers with indexed event maps preserve payload types across emit and listen boundaries, giving you autocomplete and safety for every event in your system.