Skip to content

Instantly share code, notes, and snippets.

@ger86
Created February 9, 2023 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ger86/1553a464ff8b343457d41eff09ee4141 to your computer and use it in GitHub Desktop.
Save ger86/1553a464ff8b343457d41eff09ee4141 to your computer and use it in GitHub Desktop.
Fully typed Event Dispatcher for TypeScript
type SquareEvent = { type: "square", x: number, y: number };
type CircleEvent = { type: "circle", radius: number };
type EventType = SquareEvent | CircleEvent;
type Events = {
square: SquareEvent;
circle: CircleEvent;
}
type ListenersMap = {
[E in EventType as E['type']]?: (e: E) => void;
}
class EventDispatcher {
private listenerMap: ListenersMap = {};
dispatch(event: EventType): void {
const listenerOfEvent = this.listenerMap[event.type];
listenerOfEvent?.(event as any);
}
subscribe<TEventType extends keyof ListenersMap>(type: TEventType, listener: ListenersMap[TEventType]): void {
this.listenerMap[type] = listener;
}
}
const eventDispatcher = new EventDispatcher();
eventDispatcher.dispatch({type: "square", x: 1, y: 1})
eventDispatcher.subscribe("circle", (event) => {
console.log(event);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment