Tsallaka zuwa abun ciki
Justice Tech School

Practice: Typed Event Emitter

Use a generic map of event names to payload types to make an emitter that cannot be misused.

Example
type Events = { login: string; count: number };
class Emitter {
  private h: { [K in keyof Events]?: ((p: Events[K]) => void)[] } = {};
  on<K extends keyof Events>(k: K, f: (p: Events[K]) => void) { (this.h[k] ??= []).push(f); }
  emit<K extends keyof Events>(k: K, p: Events[K]) { this.h[k]?.forEach((f) => f(p)); }
}
const e = new Emitter();
e.on("login", (u) => console.log("hello", u));
e.emit("login", "Ada");

Result

hello Ada

Exercise

Key type.

K extends  Events

Quiz Test

What does the emitter prevent?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.