0.1.0 • Published 2 years ago

@acdibble/emitter v0.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

@acdibble/emitter

A zero-overhead, type-safe event emitter

Description

This package doesn't contain any logic. It simply reexports Node.js's native EventEmitter from the events module with type info that allows for type-safe usage.

The following functions have been made type-safe:

addListener
emit
off
on
once
prependListener
prependOnceListener
removeAllListeners
removeListener

Usage

Simply define a type/interface of listener functions with the event name (or channel) as the name of the function, e.g.:

interface MessageMap {
  connect: () => void;
  disconnect: (code: number, reason?: string) => void;
}

This interface is passed as the generic paramater to the constructor function of TypeSafeEventEmitter. TypeSafeEventEmitter will take all of those functions and feed the type information into the emit and on calls.

Examples

With the following setup:

import TypeSafeEventEmitter from "@acdibble/emitter";

interface MessageMap {
  connect: () => void;
  disconnect: (code: number, reason?: string) => void;
  message: (content: string) => void;
}

const emitter = new TypeSafeEventEmitter<MessageMap>();

Listening

We can see all possible events are suggested by intellisense:

After entering the event, intellisense gives the callback signature:

All parameters are given by intellisense for the listener function:

Listeners can be declared in a non-anonymous way using the message interface:

An incorrect listener cannot be used:

Emitting

Emitting events provides the same intellisense as listening:

When emitting events, all arguments are given with their proper names and types:

All expected errors are reported, such as incorrect arity:

And incorrect types being emitted:

0.1.0

2 years ago