Table of contents

  1. 1. Problem
  2. 2. Solution

Extending the EventEmitter class from Node.js might cause error TS2307. Here is how to fix it.

Problem

In Node.js you can implement an event listener system using the EventEmitter class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {EventEmitter} from 'events';

enum TOPIC {
TEST = 'EmitterTest.TOPIC.TEST',
}

export interface EmitterTest {
on(event: TOPIC.TEST, listener: (message: string) => void): this;
}

export class EmitterTest extends EventEmitter {
public static readonly TOPIC = TOPIC;

constructor() {
super();
}

emitSomething(): void {
this.emit(EmitterTest.TOPIC.TEST, 'this-is-a-test');
};
}

// Execution

const emitter = new EmitterTest();

emitter.on(EmitterTest.TOPIC.TEST, (message) => {
console.log(`This callback received message: ${message}`);
});

emitter.emitSomething();

When executing the code above you may encounter the following errors:

error TS2307: Cannot find module ‘events’ or its corresponding type declarations.

error TS2339: Property ‘emit’ does not exist on type …

Solution

Most of the times these errors are symptoms of missing Node.js type definitions. You can resolve these problems by installing the following typings:

1
yarn add @types/node@12 --dev --tilde

Tested with TypeScript 3.9.3 and Node.js 12.18.0 LTS.