57

I have a class extends EventEmitter that can emit event hello. How can I declare the on method with specific event name and listener signature?

class MyClass extends events.EventEmitter {

  emitHello(name: string): void {
    this.emit('hello', name);
  }

  // compile error on below line
  on(event: 'hello', listener: (name: string) => void): this;
}
3
  • What's the error? And seems like your on method is lacking a body. Commented Aug 25, 2016 at 10:32
  • As @NitzanTomer said, either your on method is lacking a body, or you want to declare the event parameter as an other type than 'hello'. Commented Aug 25, 2016 at 10:44
  • 1
    This answer should help you.
    – aleclarson
    Commented Sep 14, 2018 at 21:53

7 Answers 7

110

Most usable way of doing this, is to use declare:

declare interface MyClass {
    on(event: 'hello', listener: (name: string) => void): this;
    on(event: string, listener: Function): this;
}

class MyClass extends events.EventEmitter {
    emitHello(name: string): void {
        this.emit('hello', name);
    }
}

Note that if you are exporting your class, both the interface and class have to be declared with the export keyword.

1
  • 3
    just make Update 1 the answer because the other way is more problematic. Commented Sep 26, 2018 at 8:03
73

to extend @SergeyK's answer, with this you can get type-checking and completion on both emit and on functions without repeating event types.

  1. Define event listener signatures for each event type:
interface MyClassEvents {
  'add': (el: string, wasNew: boolean) => void;
  'delete': (changedCount: number) => void;
}
  1. Declare interface which constructs types for MyClass, based on EventListeners (MyClassEvents) function signature:
declare interface MyClass {
  on<U extends keyof MyClassEvents>(
    event: U, listener: MyClassEvents[U]
  ): this;

  emit<U extends keyof MyClassEvents>(
    event: U, ...args: Parameters<MyClassEvents[U]>
  ): boolean;
}
  1. Simply define you class extending EventEmitter:
class MyClass extends EventEmitter {
  constructor() {
    super();
  }
}

Now you will get type checking for on and emit functions:

enter image description here

enter image description here

Unfortunately you will get completion and type-checking only on those two functions (unless you define more functions inside MyClass interface).

To get more generic solution, you can use this package I wrote. note: it adds no runtime overhead.

import { TypedEmitter } from 'tiny-typed-emitter';

interface MyClassEvents {
  'add': (el: string, wasNew: boolean) => void;
  'delete': (changedCount: number) => void;
}

class MyClass extends TypedEmitter<MyClassEvents> {
  constructor() {
    super();
  }
}
0
12

Here's what I was able to figure out. Overriding the default function with a generic!

interface IEmissions {
  connect: () => void
  test: (property: string) => void
}

class MyClass extends events.EventEmitter {
  private _untypedOn = this.on
  private _untypedEmit = this.emit
  public on = <K extends keyof IEmissions>(event: K, listener: IEmissions[K]): this => this._untypedOn(event, listener)
  public emit = <K extends keyof IEmissions>(event: K, ...args: Parameters<IEmissions[K]>): boolean => this._untypedEmit(event, ...args)

  this.emit('test', 'Testing') // This will be typed for you!
}

// Example:
const inst = new MyClass()
inst.on('test', info => console.log(info)) // This will be typed!
3
  • This is exactly what I needed. This gives the ability to override the functions while still enforcing the typing.
    – goodman
    Commented Mar 7, 2021 at 3:23
  • 1
    Very elegant! I have managed to even simplify this by not having to store original methods as members by simply invoking super. This worked for me in TS 4.1.3: public on<K extends keyof MyEvents>(e: K, listener: MyEvents[K]): this { return super.on(e, listener); }
    – mati.o
    Commented Sep 9, 2021 at 11:44
  • super nice version for Typescript code, using the super duplicate the line with on, off, once, emit.
    – Uriel
    Commented Mar 30, 2022 at 6:15
6

I'm not sure as of when, but this is available in the node typings now. You just have to pass a Record<string, any[]> (event-key > arguments tuple) type into the generic of EventEmitter<T>

import { EventEmitter } from 'events';

interface MyClassEvents {
  "hello": [name: string];
}

class MyClass extends EventEmitter<MyClassEvents> { }

const foo = new MyClass();

this will type the EventEmitter's methods to have these events typed for the consumer

IDE auto complete of event name

IDE showing event arg field-name and field-type infered

2
  • Yes, it works after I upgraded @types/node to current latest v20.x.x. And it seems to be the simplest way so far.
    – aleung
    Commented May 11 at 6:27
  • This method is awesome, but when we give an invalid name to emit, typescript tells us this: Argument of type '[]' is not assignable to parameter of type 'never'.ts(2345) Which is confusing. Any way to show a better error message? Commented Aug 7 at 15:44
6

You can use my typed event emitter package for this.

eg:

import { EventEmitter } from 'tsee';

const events = new EventEmitter<{
    foo: (a: number, b: string) => void,
}>();

// foo's arguments is fully type checked
events.emit('foo', 123, 'hello world');

This package also provide interfaces & some utils.

0
5

I really liked @Binier's answer and especially the generic solution offered by tiny-typed-emitter. As an alternative, I wrote up this pure-typescript version:

type EmittedEvents = Record<string | symbol, (...args: any) => any>;

export declare interface TypedEventEmitter<Events extends EmittedEvents> {
  on<E extends keyof Events>(
    event: E, listener: Events[E]
  ): this;

  emit<E extends keyof Events>(
    event: E, ...args: Parameters<Events[E]>
  ): boolean;
}

export class TypedEventEmitter<Events extends EmittedEvents> extends EventEmitter {}

It's used similarly:

type MessageSocketEvents = {
  'message': (json: object) => void;
  'close': () => void;
};

export class MessageSocket extends TypedEventEmitter<MessageSocketEvents> {
  ...
}
0
0

Something to add is, often with event emitters you'll want to conjoin a string and an enum:

type EventType<U extends string> = `${string}::${U}`;

declare interface SocketClients {
  on: <U extends keyof SocketEvents>(event: EventType<U>, listener: (args: SocketEvents[U]) => void) => this;
  emit: <U extends keyof SocketEvents>(event: EventType<U>, args: SocketEvents[U]) => boolean;
}

This will let you scope listeners, and retain typings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.