Skip to content

Instantly share code, notes, and snippets.

@jcao02
Last active September 26, 2023 13:25
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 jcao02/8748bbb56fc21bb840b59207d93e559f to your computer and use it in GitHub Desktop.
Save jcao02/8748bbb56fc21bb840b59207d93e559f to your computer and use it in GitHub Desktop.
Enum module augmentation
import { Event, Payload, bus } from './event-bus'
// Module augmentation here
declare module './event-bus' {
interface Event {
SIGN_IN: 'SIGN_IN'
SIGN_OUT: 'SIGN_OUT'
}
interface Payload {
SIGN_IN: string
}
}
bus.emit('SIGN_OUT') // Valid TS
bus.emit('SIGN_IN', 1) // Argument of type 'number' is not assignable to parameter of type 'string'.
export interface Event {
NOTIFY: 'NOTIFY'
}
export interface Payload {
NOTIFY: string
}
export type EventName = Event[keyof Event]
export type EventPayload<E> = E extends keyof Payload ? Payload[E] : unknown
type EventBus = {
subscribe<E extends EventName>(e: E, cb: (e: EventPayload<E>) => void): void
emit<E extends EventName>(e: E, payload: EventPayload<E>): void
emit<E extends EventName>(e: E): void
}
export const bus: EventBus = {
emit(e, payload?): void {
},
subscribe(e, cb) {
// Subscribe implementation
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment