Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
strict-event-emitter-types
Advanced tools
Strictly and safely type any EventEmitter-like interface on any object
The 'strict-event-emitter-types' npm package provides TypeScript types for strongly-typed event emitters. It allows developers to define event types and their corresponding payloads, ensuring type safety when emitting and listening to events.
Defining Typed Event Emitters
This feature allows you to define a typed event emitter with specific event names and their corresponding payload types. The code sample demonstrates how to create a custom event emitter class with typed events 'foo' and 'bar'.
const { EventEmitter } = require('events');
const { StrictEventEmitter } = require('strict-event-emitter-types');
interface Events {
foo: (arg: string) => void;
bar: (arg: number) => void;
}
class MyEmitter extends (EventEmitter as new () => StrictEventEmitter<EventEmitter, Events>) {}
const emitter = new MyEmitter();
emitter.on('foo', (arg) => console.log(arg));
emitter.emit('foo', 'Hello, world!');
Ensuring Type Safety
This feature ensures type safety by enforcing the correct argument types for each event. The code sample shows how TypeScript will throw an error if the argument type does not match the expected type for the event.
const { EventEmitter } = require('events');
const { StrictEventEmitter } = require('strict-event-emitter-types');
interface Events {
foo: (arg: string) => void;
bar: (arg: number) => void;
}
class MyEmitter extends (EventEmitter as new () => StrictEventEmitter<EventEmitter, Events>) {}
const emitter = new MyEmitter();
// TypeScript will throw an error if the argument type does not match
// emitter.emit('foo', 123); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
emitter.emit('foo', 'Hello, world!');
Typed Event Listeners
This feature allows you to define typed event listeners, ensuring that the callback functions match the expected argument types for each event. The code sample demonstrates how TypeScript will throw an error if the listener callback does not match the expected type.
const { EventEmitter } = require('events');
const { StrictEventEmitter } = require('strict-event-emitter-types');
interface Events {
foo: (arg: string) => void;
bar: (arg: number) => void;
}
class MyEmitter extends (EventEmitter as new () => StrictEventEmitter<EventEmitter, Events>) {}
const emitter = new MyEmitter();
// TypeScript will throw an error if the listener callback does not match the expected type
// emitter.on('foo', (arg: number) => console.log(arg)); // Error: Argument of type '(arg: number) => void' is not assignable to parameter of type '(arg: string) => void'.
emitter.on('foo', (arg: string) => console.log(arg));
The 'typed-emitter' package provides a similar functionality by allowing you to create strongly-typed event emitters in TypeScript. It offers a more modern API and better integration with TypeScript's type system compared to 'strict-event-emitter-types'.
The 'eventemitter3' package is a lightweight and fast event emitter implementation. While it does not provide built-in TypeScript type safety, it can be extended with custom TypeScript types to achieve similar functionality as 'strict-event-emitter-types'.
The 'mitt' package is a tiny functional event emitter. It is not strictly typed out of the box, but you can use TypeScript's type system to create type-safe event emitters similar to 'strict-event-emitter-types'.
NOTE: REQUIRES TYPESCRIPT 2.8 SUPPORT FOR CONDITIONAL TYPES
A TypeScript library for strongly typed event emitters in 0 kB. Works with any kind of EventEmitter.
npm i strict-event-emitter-types
import StrictEventEmitter from 'strict-event-emitter-types';
// grab your event emitter
import { EventEmitter } from 'events';
// define your events
interface Events {
newValue: number,
done: void // an event with no payload
}
// Create a typed event emitter
let ee: StrictEventEmitter<EventEmitter, Events> = new EventEmitter;
// now enjoy your strongly typed EventEmitter API!
ee.on('newValue', x => x); // x is contextually typed to number
ee.on('somethingElse'); // Error: unknown event
ee.on('done', x => x); // Error: 'done' does not have a payload
ee.emit('newValue', 'hello!'); // Error: incorrect payload
ee.emit('newValue'); // Error: forgotten payload
The default export. A generic type that takes three type parameters:
The third parameter is handy when typing web sockets where client and server can listen to and emit different events. For example, if you are using socket.io:
// create types representing the server side and client
// side sockets
export type ServerSocket =
StrictEventEmitter<SocketIO.Socket, EventsFromServer, EventsFromClient>;
export type ClientSocket =
StrictEventEmitter<SocketIOClient.Socket, EventsFromClient, EventsFromServer>;
// elsewhere on server
let serverSocket: ServerSocket = new SocketIO.Socket();
serverSocket.on(/* only events that are sent from the client are allowed */, ...)
serverSocket.emit(/* only events that are emitted from the server are allowed */, ...)
// elsewhere on client
let clientSocket: ClientSocket = new SocketIOClient.Socket();
clientSocket.on(/* only events that are sent from the server are allowed */, ...)
clientSocket.emit(/* only events that are emitted from the client are allowed */, ...)
A type for a function which takes (and strictly checks) an emit event and a payload. TStrictEventEmitter is the event emitter type instantiated from StrictEventEmitter.
Useful for broadcast abstractions. It is not possible to contextually type assigments to this type, so your declarations will look something like this:
import { StrictBroadcast } from 'strict-event-emitter-types';
const broadcast: StrictBroadcast<ServerSocket> = function (event: string, payload?: any) {
// ...
}
Note that the loose types for event and payload only apply inside the broadcast function (consumers will see a much stricter signature). Declaring more precise parameter types or narrowing using type guards would allow strongly-typed dispatching to emitters.
FAQs
Strictly and safely type any EventEmitter-like interface on any object
The npm package strict-event-emitter-types receives a total of 0 weekly downloads. As such, strict-event-emitter-types popularity was classified as not popular.
We found that strict-event-emitter-types demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.