Strict Event Emitter
EventEmitter
mirror that restricts emitting/handling events other than specified in an interface.
Features
- Restricts emitting of the unknown event types.
- Infers emitted data types from the listener's call signature.
Motivation
The native EventEmitter
class uses a generic string
to describe what type of events can be emitted. In most cases you design a strict set of events that you expect your emitter to emit/listen to. This package helps you to type-annotate an emitter instance to produce type violations if an unknown event is emitted/listened to.
const emitter = new EventEmitter()
emitter.addListener('ping', (n: number) => {})
emitter.emit('pong', 'not a number')
import { StrictEventEmitter } from 'strict-event-emitter'
interface EventsMap {
ping: (n: number) => void
}
const emitter = new StrictEventEmitter<EventsMap>()
emitter.addListener('ping', (n) => {
})
emitter.emit('ping', 10)
emitter.emit('ping', 'wait, not a number')
emitter.emit('unknown', 10)
This library is a superset class of the native EventEmitter
with only the type definition logic attached. There's no additional functionality present.
Getting started
Install
npm install strict-event-emitter
Use
import { StrictEventEmitter } from 'strict-event-emitter'
interface EventsMap {
connect: (id: string) => void
disconnect: (id: string) => void
}
const emitter = new StrictEventEmitter<EventsMap>()
emitter.addListner('connect', (id) => {})
emitter.emit('connect', 'abc-123')
License
MIT