0Pricing
TypeScript Academy · Lesson

Type-Safe emit and on

Enforce correct payloads when emitting and listening.

A Type-Safe emit Signature

Make emit generic over the event name K. The payload parameter is then Events[K], so name and payload must match.

interface Events { login: { userId: string }; logout: void }
function emit<K extends keyof Events>(event: K, payload: Events[K]) {
  console.log("emit", event, JSON.stringify(payload));
}
emit("login", { userId: "u1" });

Wrong Payload Is a Compile Error

If the payload does not match the event name, TypeScript rejects it. The generic links the two parameters.

interface Events { login: { userId: string } }
function emit<K extends keyof Events>(event: K, payload: Events[K]) {}
// emit("login", { id: "u1" }); // Error: id is not userId
emit("login", { userId: "u1" });
console.log("ok");

All lessons in this course

  1. Typing Event Maps
  2. Type-Safe emit and on
  3. Generic Event Emitter Class
  4. Inferring Listener Arguments
← Back to TypeScript Academy