typestar

Tiny event emitter in TypeScript

An event emitter where the event name determines the payload type.

type Listener<T> = (payload: T) => void;

class Emitter<T> {
  private listeners: Listener<T>[] = [];

  on(listener: Listener<T>): void {
    this.listeners.push(listener);
  }

  emit(payload: T): void {
    for (const listener of this.listeners) {
      listener(payload);
    }
  }
}

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
259
Tokens
82
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 2 of 2 in Typed events, step 4 of 8 in Async & modules.

← Previous Next →