2.1.0 • Published 2 years ago

typed-emitter v2.1.0

Weekly downloads
24,040
License
MIT
Repository
github
Last release
2 years ago

Typed-Emitter

NPM Version

Strictly typed event emitter interface for TypeScript.

Code size: Zero bytes - Just the typings, no implementation. Use the default event emitter of the events module in node.js or bring your favorite implementation when writing code for the browser.

Installation

$ npm install --save-dev typed-emitter

# Using yarn:
$ yarn add --dev typed-emitter

Usage

import EventEmitter from "events"
import TypedEmitter from "typed-emitter"

// Define your emitter's types like that:
// Key: Event name; Value: Listener function signature
type MessageEvents = {
  error: (error: Error) => void,
  message: (body: string, from: string) => void
}

const messageEmitter = new EventEmitter() as TypedEmitter<MessageEvents>

// Good 👍
messageEmitter.emit("message", "Hi there!", "no-reply@test.com")

// TypeScript will catch those mistakes ✋
messageEmitter.emit("mail", "Hi there!", "no-reply@test.com")
messageEmitter.emit("message", "Hi there!", true)

// Good 👍
messageEmitter.on("error", (error: Error) => { /* ... */ })

// TypeScript will catch those mistakes ✋
messageEmitter.on("error", (error: string) => { /* ... */ })
messageEmitter.on("failure", (error: Error) => { /* ... */ })

Extending an emitter

You might find yourself in a situation where you need to extend an event emitter, but also want to strictly type its events. Here is how to.

class MyEventEmitter extends (EventEmitter as new () => TypedEmitter<MyEvents>) {
  // ...
}

As a generic class:

class MyEventEmitter<T> extends (EventEmitter as { new<T>(): TypedEmitter<T> })<T> {
  // ...
}

RxJS fromEvent types inference

The default fromEvent from RxJS will return an Observable<unknown> for our typed emitter.

This can be fixed by the following code, by replacing the fromEvent type with our enhanced one: FromEvent:

import { fromEvent as rxFromEvent } from "rxjs"
import { default as TypedEmitter, FromEvent } from "typed-emitter/rxjs"

// The `Observable` typing can be correctly inferenced
const fromEvent = rxFromEvent as FromEvent

Learn more from rxjs fromEvent compatibility #9 for the fromEvent compatibility discussions.

Why another package?

The interface that comes with @types/node is not type-safe at all. It does not even offer a way of specifying the events that the emitter will emit...

The eventemitter3 package is a popular event emitter implementation that comes with TypeScript types out of the box. Unfortunately there is no way to declare the event arguments that the listeners have to expect.

There were a few other examples of type-safe event emitter interfaces out there as well. They were either not published to npm, had an inconsistent interface or other limitations.

License

MIT

@herman-bilous/livekit-clientdiscord-irisicqjs@rqbik/icqjsfrontity-k8s-not-meant-to-be-usefullinkbox-rtc-clienteasy-chat-bot-managerkit-client@fsp-fs/electron-updatersl-commands@everything-registry/sub-chunk-2993ally-clientwallet-connect-sdk-core@davmixcool/stability-ts@dkaframework/iot@dkaframework/serverdecorator-builderdignissimosest@datastax/astra-db-ts@depyronick/stability-clientffmpeggyfast-iterableext-portfastify-webpack-hotfridgefm-radio-corefrida-sidecarfrida-compilefrontitydms-game-clientdjs-userdjs-minigamesel-page-pagetableelectron-update-checker-notifierelectron-updater-with-giteaemiteratoreventify-function@hedgedoc/realtime-communication@gigglebot/wrapperhyper-express@guildedjs/api@guildedjs/gil@guildedjs/rest@guildedjs/wsinwatchinstagram-connecthypixel-proxyhomebridge-lutron-caseta-leaphomebridge-lutron-caseta-leap-fasthomebridge-lutron-radiora3@goldskycom/pg-listen@huma-shan/ethereum-storage@huma-shan/thegraph-data-accessdsbotxdynamo-http@cloudcue/client-contractsedge-impulse-apiedge-impulse-api-testedge-impulse-linuxedge-impulse-linux-testelectron-app-universal-protocol-client@empirica/tajribaguilded.js@eslym/youtube-chat@electron-boot/updater@elwood-studio/workflow-runner@eslym/youtube-utilities@egy186/julius-client@dxxxxy/mineflayer@eggjs/eventbus-decoratorhao-balancehendricks-bothendricks-pdkgeoally-client@dtelecom/livekit-unityhappy-feet@fermuch/monoutils@fermuch/telematree@flysoftbeta/qqntim-typings@framelabs/pylon-client@fridgefm/radio-core@frinkly/thegraph-data-access@frinkly/ethereum-storage@fosh/chat-clienthomebridge-plugin-anova-toast@fyko/export-api@iameli/api@iameli/bsky@iameli/bsync@iameli/ozone@iameli/pds@inboxsdk/corejylive-client@jellyfish-dev/membrane-webrtc-js@jellyfish-dev/ts-client-sdk@infinitebrahmanuniverse/nolb-typed@juzi/wechaty-puppet@juzi/wechaty-puppet-mock@juzi/wechaty-reduxkislkafka-sagas
2.1.0

2 years ago

2.0.0

2 years ago

1.5.0-from-event

2 years ago

1.4.0

3 years ago

1.3.1

4 years ago

1.3.0

4 years ago

1.2.0

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago

0.2.0

5 years ago

0.1.0

6 years ago

0.0.2

8 years ago

0.0.1

8 years ago