Created
February 9, 2023 10:09
-
-
Save ger86/1553a464ff8b343457d41eff09ee4141 to your computer and use it in GitHub Desktop.
Fully typed Event Dispatcher for TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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