• Stars
    star
    250
  • Rank 156,326 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ”ฉ Type-safe event emitter interface for TypeScript

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!", "[email protected]")

// TypeScript will catch those mistakes โœ‹
messageEmitter.emit("mail", "Hi there!", "[email protected]")
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

More Repositories

1

webpack-blocks

๐Ÿ“ฆ Configure webpack using functional feature blocks.
JavaScript
2,979
star
2

threads.js

๐Ÿงต Make web workers & worker threads as simple as a function call.
TypeScript
2,942
star
3

leakage

๐Ÿ› Memory leak testing for node.
JavaScript
1,583
star
4

pg-listen

๐Ÿ“ก PostgreSQL LISTEN & NOTIFY for node.js that finally works.
TypeScript
540
star
5

use-inline-memo

โš›๏ธ React hook for memoizing values inline anywhere in a component
TypeScript
163
star
6

postguard

๐Ÿ› Statically validate Postgres SQL queries in JS / TS code and derive schemas.
TypeScript
161
star
7

laravel-js-localization

Simple, ease-to-use and flexible package for the Laravel web framework. Allows you to use localized messages of the Laravel webapp (see `resources/lang` directory) in your Javascript code.
PHP
143
star
8

squid

๐Ÿฆ‘ Provides SQL tagged template strings and schema definition functions.
TypeScript
124
star
9

ava-ts

๐Ÿš€ Fork of the AVA test runner with native typescript support
JavaScript
116
star
10

postcss-debug

Debug your postcss workflow with ease! Creates snapshots of your CSS files before/after each postcss plugin is run.
JavaScript
94
star
11

react-usestyles

๐Ÿ– Style components using React hooks. Abstracts the styling library away.
JavaScript
87
star
12

postcss-theme

PostCSS plugin to enable versatile theming.
JavaScript
87
star
13

react-stateful-fn

โš› Stateful functional components for React.
JavaScript
57
star
14

puppet-run

๐Ÿค– Run anything JavaScript in a headless Chrome from your command line
TypeScript
53
star
15

threadpool-js

Javascript thread pool implementation using web workers.
JavaScript
47
star
16

jquery-dim-background

jQuery plugin to dim the current page except for some user-defined top elements.
JavaScript
43
star
17

observable-fns

๐Ÿ•ต๏ธโ€โ™€๏ธ Light-weight observable implementation and functional utilities in TypeScript
TypeScript
41
star
18

npm-launch

๐Ÿš€ Minimalistic task runner on steroids!
JavaScript
39
star
19

drag-mock

Trigger HTML5 drag & drop events for testing
JavaScript
35
star
20

gear

๐Ÿ›  Experimental tool to bootstrap typed JavaScript code.
JavaScript
33
star
21

proposal-double-colon-types

๐Ÿค“ JS / Flow syntax proposal. Types ร  la Hindley-Milner.
20
star
22

http-event-stream

๐Ÿ“ก Modern spec-compliant Server Sent Events stream implementation.
TypeScript
19
star
23

ts

โš™๏ธ The CLI that TypeScript deserves.
TypeScript
18
star
24

key-store

๐Ÿ” Isomorphic encrypted key store written in TypeScript.
TypeScript
17
star
25

plow

๐Ÿ‘จโ€๐ŸŒพ Postgres migrations and seeding made easy
TypeScript
14
star
26

isomorphic-crypto

๐Ÿ”’ Isomorphic crypto package for node and the browser.
JavaScript
12
star
27

type-reflect

โ˜๏ธ TypeScript plugin providing access to type information at runtime
TypeScript
11
star
28

srv

๐Ÿ“ก Functional node server. Composable routing. Take a request, return a response.
TypeScript
9
star
29

rungpt

GPT client with local plugin framework, built by GPT-4
TypeScript
9
star
30

php-easygit

Manage Git repositories from within your PHP webapp. Commit, branch, clone, checkout, ...
PHP
7
star
31

zaster

๐Ÿ’ธ Headless multi-blockchain wallet and SDK.
TypeScript
7
star
32

react-commandments

๐Ÿ“– Thou shalt honor thy reactive code and keep it holy.
6
star
33

koa-router-index

Koa v2 middleware to create an index page for API servers.
JavaScript
5
star
34

gulp-elixir-modules

Elixir extension for handling frontend modules easily.
JavaScript
5
star
35

json-sql-import

Small PHP tool to import JSON data into database tables using transformation rules.
PHP
4
star
36

puppet-run-plugins

๐Ÿงฉ Plugins for puppet-run.
TypeScript
4
star
37

shutter-legacy

๐Ÿ“ธ Visual snapshot testing with no effort.
TypeScript
3
star
38

deep-assert

๐Ÿ” Better deep-equals comparison, supporting custom property assertions and pretty diffs.
TypeScript
3
star
39

ideabox

Place to collect techy ideas and get feedback.
1
star
40

bundle-decomposition-research

JavaScript
1
star
41

stellar-wallet

With the new Stellar wallet to the moon ๐Ÿš€
JavaScript
1
star