Search code examples
node.jstypescript

Declaring events in a TypeScript class which extends EventEmitter


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;
}

Solution

  • 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.