Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to make eventemitter3 typesafe
import EventEMitter3 from 'eventemitter3'
interface EmitterEvent<Type extends string> extends Object {
type: Type;
}
interface AEvent extends EmitterEvent<'a'>{
aOnly: true
}
interface BEvent extends EmitterEvent<'b'>{
bOnly: true
}
type EmitterEvents =
| AEvent
| BEvent
class Emitter extends EventEMitter3<EmitterEvents['type']> {
on<Type extends EmitterEvents['type']>(name: Type, callback: (evt: Extract<EmitterEvents, {type: Type}>) => void) {
return super.on(name, callback)
}
emit<Type extends EmitterEvents['type']>(name: Type, evt: Omit<Extract<EmitterEvents, {type: Type}>, 'type'>) {
return super.emit(name, evt)
}
}
const em = new Emitter()
em.on('a', (evt) => {
evt.aOnly
// @ts-expect-error
evt.bOnly
})
em.on('b', (evt) => {
evt.bOnly
// @ts-expect-error
evt.aOnly
})
// @ts-expect-error
em.on('c', (evt) => {
// c doesn't exist
})
em.emit('a', {aOnly: true})
// @ts-expect-error
em.emit('b', {aOnly: true})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment