Last active
September 26, 2023 13:25
-
-
Save jcao02/8748bbb56fc21bb840b59207d93e559f to your computer and use it in GitHub Desktop.
Enum module augmentation
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
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'. |
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
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