Skip to content

Instantly share code, notes, and snippets.

@fjahn
Created September 27, 2022 13:10
Show Gist options
  • Save fjahn/853f277eda907453e3f46055b299c3bb to your computer and use it in GitHub Desktop.
Save fjahn/853f277eda907453e3f46055b299c3bb to your computer and use it in GitHub Desktop.
Typesafe Event Emitter
export class OpenEventEmitter<T> implements EventEmitter<T> {
private readonly handlers: { [eventName in keyof T]?: ((value: T[eventName]) => void)[] }
constructor() {
this.handlers = {}
}
getClosedEmitter(): EventEmitter<T> {
return this
}
emit<K extends keyof T>(event: K, value: T[K]): void {
this.handlers[event]?.forEach(h => h(value))
}
on<K extends keyof T>(event: K, handler: (value: T[K]) => void): void {
if(!this.handlers[event])
this.handlers[event] = []
this.handlers[event]?.push(handler)
}
}
export default interface EventEmitter<T> {
on<K extends keyof T>(event: K, handler: (value: T[K]) => void): void
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment