Typed Event Emitter With Event Maps
Type an event emitter against an event map so emitting or subscribing with a wrong event name or payload is a compile error.
Code
type EventMap = {
open: { id: string };
close: { id: string; reason: string };
tick: number;
};
class TypedEmitter<T extends Record<string, unknown>> {
private handlers: { [K in keyof T]?: Array<(payload: T[K]) => void> } = {};
on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): () => void {
(this.handlers[event] ??= []).push(handler);
return () => {
this.handlers[event] = this.handlers[event]?.filter((h) => h !== handler);
};
}
emit<K extends keyof T>(event: K, payload: T[K]): void {
for (const handler of this.handlers[event] ?? []) handler(payload);
}
}
const bus = new TypedEmitter<EventMap>();
const off = bus.on('open', ({ id }) => console.log('opened', id));
bus.on('tick', (n) => console.log('tick', n));
bus.emit('open', { id: 'conn-1' });
bus.emit('tick', 1);
off();
// bus.emit('close', { id: 'x' }); // 缺 reason:编译错误
// bus.emit('unknown', 1); // 未知事件名:编译错误
console.log('handlers wired');Output
Captured from a sandboxed run of this snippet in the build pipeline.
opened conn-1
tick 1
handlers wiredWhat the code does
The moving parts are the class TypedEmitter.
Repetition is confined to for (const handler of this.handlers[event] ?? []) handler(payload); — the rest of the file is straight-line.
Module-level bindings hold the data — bus, off — with no function scope in between.
Applying it
Running the file prints labeled results such as opened, tick, handlers wired — each operation’s effect is visible in the output.
Statements that matter
on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): () => void {
(this.handlers[event] ??= []).push(handler);
return () => {
this.handlers[event] = this.handlers[event]?.filter((h) => h !== handler);
};
}
private handlers: { [K in keyof T]?: Array<(payload: T[K]) => void> } = {};
for (const handler of this.handlers[event] ?? []) handler(payload);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `bus`, `off`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.