Type-Safe Event Map Emitter
Bind event names to their payload types in one map so listeners and emitters are checked together and misspelled events fail to compile.
Code
type EventMap = {
login: { userId: string };
logout: { userId: string; reason: string };
error: { message: string; retryable: boolean };
};
export class TypedEmitter<M extends Record<string, unknown>> {
private handlers: { [K in keyof M]?: Array<(payload: M[K]) => void> } = {};
on<K extends keyof M>(event: K, handler: (payload: M[K]) => void): void {
(this.handlers[event] ??= []).push(handler);
}
emit<K extends keyof M>(event: K, payload: M[K]): void {
for (const handler of this.handlers[event] ?? []) handler(payload);
}
}
export const emitter = new TypedEmitter<EventMap>();How it works
Count the class TypedEmitter as the entire surface area of Type-Safe Event Map Emitter.
The file repeats itself only inside for (const handler of this.handlers[event] ?? []) handler(payload);.
Applying it
TypedEmitter is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
private handlers: { [K in keyof M]?: Array<(payload: M[K]) => void> } = {};
on<K extends keyof M>(event: K, handler: (payload: M[K]) => void): void {
(this.handlers[event] ??= []).push(handler);
}
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring.
Report a problem with this exampleOpens a pre-filled issue on GitHub.