Typed Event Emitter With Event Maps

Type an event emitter against an event map so emitting or subscribing with a wrong event name or payload is a compile error.

TypescriptData Integrity

Code

typescriptsnippet
31 lines
type EventMap = {
  open: { id: string };
  close: { id: string; reason: string };
  tick: number;
};

class TypedEmitter<T extends Record<string, unknown>> {
  private handlers: { [K in keyof T]?: Array<(payload: T[K]) => void> } = {};

  on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): () => void {
    (this.handlers[event] ??= []).push(handler);
    return () => {
      this.handlers[event] = this.handlers[event]?.filter((h) => h !== handler);
    };
  }

  emit<K extends keyof T>(event: K, payload: T[K]): void {
    for (const handler of this.handlers[event] ?? []) handler(payload);
  }
}

const bus = new TypedEmitter<EventMap>();
const off = bus.on('open', ({ id }) => console.log('opened', id));
bus.on('tick', (n) => console.log('tick', n));

bus.emit('open', { id: 'conn-1' });
bus.emit('tick', 1);
off();
// bus.emit('close', { id: 'x' });      // 缺 reason:编译错误
// bus.emit('unknown', 1);              // 未知事件名:编译错误
console.log('handlers wired');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

opened conn-1
tick 1
handlers wired

What the code does

The moving parts are the class TypedEmitter.

Repetition is confined to for (const handler of this.handlers[event] ?? []) handler(payload); — the rest of the file is straight-line.

Module-level bindings hold the data — bus, off — with no function scope in between.

Applying it

Running the file prints labeled results such as opened, tick, handlers wired — each operation’s effect is visible in the output.

Statements that matter

on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): () => void {
(this.handlers[event] ??= []).push(handler);
return () => {
this.handlers[event] = this.handlers[event]?.filter((h) => h !== handler);
};
}
private handlers: { [K in keyof T]?: Array<(payload: T[K]) => void> } = {};
for (const handler of this.handlers[event] ?? []) handler(payload);

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `bus`, `off`.