Typed Event Emitter

Implements a strongly typed event emitter for use in applications.

TypeScript
david

13 weeks ago

type EventMap = Record<string, (...args: any[]) => void>;

class TypedEventEmitter<T extends EventMap> {
  private listeners: { [K in keyof T]?: T[K][] } = {};

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

  emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>): void {
    this.listeners[event]?.forEach((listener) => listener(...args));
  }
}
0