Strictly Typed Event Emitter Interface

2.1.0 · active · verified Sun Apr 19

Typed-emitter is a lightweight TypeScript-only package (zero runtime bytes) that provides a strictly typed interface for event emitters. It is currently stable at version 2.1.0, receiving minor updates for bug fixes and feature enhancements, with occasional breaking changes primarily around type constraints or specific integration points like RxJS. Unlike `@types/node` which offers loose typings, or `eventemitter3` which lacks strong argument typing, typed-emitter allows developers to define a precise `EventMap` for their emitter instances. This enables compile-time verification of event names and listener argument signatures, preventing common runtime errors. It's designed to be used with existing `EventEmitter` implementations, such as Node.js's built-in `events` module or browser-based alternatives, without providing its own implementation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining event map types and applying them to a standard Node.js EventEmitter, showcasing compile-time type checking for `emit` and `on` calls.

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

type MessageEvents = {
  error: (error: Error) => void;
  message: (body: string, from: string) => void;
  statusUpdate: (status: 'online' | 'offline') => void;
};

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

// Good: TypeScript validates event name and argument types
messageEmitter.emit("message", "Hi there!", "no-reply@test.com");
messageEmitter.emit("statusUpdate", "online");

// TypeScript will catch type mistakes
// @ts-expect-error Argument of type 'boolean' is not assignable to parameter of type 'string'.
messageEmitter.emit("message", "Hi there!", true);
// @ts-expect-error Argument of type 'string' is not assignable to parameter of type '"online" | "offline"'.
messageEmitter.emit("statusUpdate", "connecting");

// Good: Type-safe listener registration
messageEmitter.on("error", (error: Error) => { console.error(error.message); });

// TypeScript will catch mistakes in listener signatures
// @ts-expect-error Argument of type 'string' is not assignable to parameter of type 'Error'.
messageEmitter.on("error", (error: string) => { /* ... */ });

console.log('Typed emitter setup successfully.');
// To prevent process from exiting immediately in Node.js
setInterval(() => {}, 1000);

view raw JSON →