BeginnerCoder

Lesson 25 — Ultimate: typed event emitter

Boss level: a fully typed event bus

An event emitter (or bus) lets parts of an app talk without knowing each other: some code calls on(name, handler) to listen, other code calls emit(name, data). An event map type lists every event name with its data type, and generics with K extends keyof E make sure emit("login", …) gets exactly the login data and each handler receives the right type.

type Events = { saved: { id: number } };
bus.on("saved", (d) => d.id);   // d is { id: number }
// bus.emit("saved", { id: "x" }); ← error

Why it matters: this is production-grade type safety for the event systems in UI libraries and Node.

Want it another way?
Task

Finish emit so it calls every handler registered for that event. Expect welcome Sam, then bye.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.