0
0
Typescriptprogramming~10 mins

Type-safe event emitter pattern in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type-safe event emitter pattern
Define Event Types
Create Emitter Class
Add Listener with Type
Emit Event with Payload
Listener Receives Typed Payload
Process Event
End
This flow shows how to define event types, create a typed emitter, add listeners, emit events, and handle typed payloads safely.
Execution Sample
Typescript
interface Events {
  login: { user: string };
  logout: {};
}

class TypedEmitter<T> {
  private listeners: { [K in keyof T]?: ((payload: T[K]) => void)[] } = {};

  on<K extends keyof T>(eventName: K, listener: (payload: T[K]) => void): void {
    if (!this.listeners[eventName]) {
      this.listeners[eventName] = [];
    }
    this.listeners[eventName]!.push(listener);
  }

  emit<K extends keyof T>(eventName: K, payload: T[K]): void {
    if (!this.listeners[eventName]) return;
    for (const listener of this.listeners[eventName]!) {
      listener(payload);
    }
  }
}

const emitter = new TypedEmitter<Events>();
emitter.on('login', data => console.log(data.user));
emitter.emit('login', { user: 'Alice' });
This code defines event types, creates a typed emitter, adds a listener for 'login', and emits a 'login' event with a typed payload.
Execution Table
StepActionEvent TypePayloadListener CalledOutput
1Create TypedEmitter instance--No-
2Add listener for 'login'login-No-
3Emit 'login' eventlogin{ user: 'Alice' }YesConsole logs 'Alice'
4Listener processes payloadlogin{ user: 'Alice' }YesOutput: Alice
5No more events--NoEnd of execution
💡 No more events to emit, execution ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
emitterundefinedTypedEmitter instanceListeners for 'login' addedListeners triggeredTypedEmitter instance
listeners['login']undefinedundefined1 listener functionListener called1 listener function
Key Moments - 2 Insights
Why does the listener only accept a specific payload shape?
Because the TypedEmitter uses the Events interface to enforce that listeners for 'login' receive exactly { user: string }, as shown in execution_table step 3 and 4.
What happens if we try to emit an event with wrong payload?
TypeScript will show an error before running, preventing emit calls with wrong payload types, ensuring type safety as seen in the code sample.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the listener for 'login' added?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Check the 'Action' column in execution_table for when listeners are added.
According to variable_tracker, what is the state of listeners['login'] after Step 3?
ANo listeners
BListener called
CListener function added but not called
DListeners removed
💡 Hint
Look at the 'After Step 3' column for listeners['login'] in variable_tracker.
If we emit 'logout' event with an empty payload, what will happen?
AListener for 'login' is called
BType error because payload is empty
CNo listener is called if none registered for 'logout'
DEmit fails silently
💡 Hint
Refer to the concept that listeners are called only if registered for that event type.
Concept Snapshot
Type-safe event emitter pattern in TypeScript:
- Define event types in an interface
- Create TypedEmitter class with generic event map
- Add listeners with .on(event, callback) typed by event
- Emit events with .emit(event, payload) enforcing payload type
- Ensures listeners receive correct payload shape
- Prevents runtime errors by compile-time checks
Full Transcript
This visual execution shows how a type-safe event emitter works in TypeScript. First, we define an interface with event names and their payload types. Then, we create a TypedEmitter instance. We add a listener for the 'login' event that expects a payload with a user string. When we emit the 'login' event with the correct payload, the listener is called and logs the user name. The variable tracker shows how the emitter and listeners change state step by step. Key moments clarify why payload types are enforced and what happens if wrong payloads are used. The quiz tests understanding of listener addition, listener call state, and behavior when emitting events without listeners. This pattern helps catch errors early and keeps event handling safe and clear.