Back to Snippets
Type-Safe Event Emitter
typescript
TypeScript
A fully typed event emitter for TypeScript applications.
Code
1type EventMap = Record<string, any>;
2type EventKey<T extends EventMap> = string & keyof T;
3type EventCallback<T> = (payload: T) => void;
4
5class TypedEventEmitter<T extends EventMap> {
6private listeners: { [K in keyof T]?: EventCallback<T[K]>[] } = {};
7
8on<K extends EventKey<T>>(event: K, callback: EventCallback<T[K]>): void {
9if (!this.listeners[event]) {
10this.listeners[event] = [];
11}
12this.listeners[event]!.push(callback);
13}
14
15emit<K extends EventKey<T>>(event: K, payload: T[K]): void {
16this.listeners[event]?.forEach(callback => callback(payload));
17}
18
19off<K extends EventKey<T>>(event: K, callback: EventCallback<T[K]>): void {
20this.listeners[event] = this.listeners[event]?.filter(cb => cb !== callback);
21}
22}
23
24// Usage
25interface AppEvents {
26userLogin: { userId: string; timestamp: Date };
27dataLoaded: { count: number };
28}
29
30const emitter = new TypedEventEmitter<AppEvents>();
31emitter.on("userLogin", ({ userId }) => console.log(userId));Details
Language
typescript
Category
TypeScript