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
- Typing Event Maps
- Type-Safe emit and on
- Generic Event Emitter Class
- Inferring Listener Arguments