Skip to content

Instantly share code, notes, and snippets.

@nhrones
Created July 25, 2023 23:25
Show Gist options
  • Save nhrones/409268659347ba17a8562a680a0663b2 to your computer and use it in GitHub Desktop.
Save nhrones/409268659347ba17a8562a680a0663b2 to your computer and use it in GitHub Desktop.
EventBus Types
/**
* type for generic Event-Handler callbacks
*/
export type EventHandler<T = any> = (data: T) => void;
/**
* validate each Event Types callback parameters
*/
export type EventContract<T> = { [K in keyof T]: T[K] }
/**
* An EventBus interface with typed events and callbacks
*/
export interface EventBus<T extends EventContract<T>> {
/**
* register a callback for specific named event
*/
when<K extends keyof T>(event: K, id: string, handler: EventHandler<T[K]>): void,
/**
* fire a specific named event with an appropriate payload
*/
send<K extends keyof T>(event: K, id: string, args: T[K]): void
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment