Typed event emitters
npm install main-event

> Typed event emitters
Adds types to the EventTarget class.
Hopefully this won't be necessary
forever:
-
-
-
-
-
-
- etc
In addition to types, a safeDispatchEvent method is available which
prevents dispatching events that aren't in the event map, and alistenerCount method which reports the number of listeners that are
currently registered for a given event.
``ts
import { TypedEventEmitter } from 'main-event'
import type { TypedEventTarget } from 'main-event'
interface EventTypes {
'test': CustomEvent
}
const target = new TypedEventEmitter
// it's a regular EventTarget
console.info(target instanceof EventTarget) // true
// register listeners normally
target.addEventListener('test', (evt) => {
// evt is CustomEvent
})
// @ts-expect-error 'derp' is not in the event map
target.addEventListener('derp', () => {})
// use normal dispatchEvent method
target.dispatchEvent(new CustomEvent('test', {
detail: 'hello'
}))
// use type safe dispatch method
target.safeDispatchEvent('test', {
detail: 'world'
})
// report listener count
console.info(target.listenerCount('test')) // 0
// event emitters can be used purely as interfaces too
function acceptTarget (target: TypedEventTarget
// ...
}
`
`console`
$ npm i main-event
Licensed under either of
- Apache 2.0, (LICENSE-APACHE /
- MIT (LICENSE-MIT /
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.