Type-Safe Event Map Emitter

Bind event names to their payload types in one map so listeners and emitters are checked together and misspelled events fail to compile.

TypescriptResilience

Code

typescriptsnippet
19 lines
type EventMap = {
  login: { userId: string };
  logout: { userId: string; reason: string };
  error: { message: string; retryable: boolean };
};

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

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

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

export const emitter = new TypedEmitter<EventMap>();

How it works

Count the class TypedEmitter as the entire surface area of Type-Safe Event Map Emitter.

The file repeats itself only inside for (const handler of this.handlers[event] ?? []) handler(payload);.

Applying it

TypedEmitter is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring.