I've been working on implementing an event emitter, and the code is pretty straightforward.
Currently, tsc
is flagging the event type in eventHandler
as 'ErrorEvent' | 'MessageEvent'
. This seems to be causing some confusion, and I'm looking for a way to get tsc
to narrow down the types correctly based on the eventName
passed to the on
function.
Is there a solution to this issue?
Here are the Definitions:
interface Event {
code: string;
}
interface ErrorEvent extends Event {
xxx: number;
}
interface MessageEvent extends Event {
yyy: number;
}
interface Events {
error: ErrorEvent,
message: MessageEvent
}
type EventHandler = (event: Events[keyof Events]) => void;
Here's the TS CODE:
function on (eventName: keyof Events, eventHandler: EventHandler) {
console.log(eventName)
}
on('message', (event) => { // ErrorEvent | MessageEvent
console.log(event)
console.log(event.code)
console.log(event.xxx) // Property 'xxx' does not exist on type 'ErrorEvent | MessageEvent'.
console.log(event.yyy) // Property 'yyy' does not exist on type 'ErrorEvent | MessageEvent'.
})