Skip to content

Instantly share code, notes, and snippets.

@ericwooley
Last active March 19, 2021 07:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericwooley/6c00b61dee8ef7f61d73c4737f115faf to your computer and use it in GitHub Desktop.
Save ericwooley/6c00b61dee8ef7f61d73c4737f115faf to your computer and use it in GitHub Desktop.
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