iooi
iooi

Reputation: 523

How to avoid EventEmitter type error in TypeScript?

In a typescript source src/index.ts, using EventEmitter. When run typecheck

yarn workspace my_project typecheck

Got error

yarn workspace v1.22.10
yarn run v1.22.10
$ tsc --noEmit
src/index.ts:28:4 - error TS2709: Cannot use namespace 'EventEmitter' as a type.

28 ): EventEmitter {
      ~~~~~~~~~~~~

src/index.ts:30:24 - error TS2351: This expression is not constructable.
  Type 'typeof EventEmitter' has no construct signatures.

30   const eventHub = new EventEmitter()
                          ~~~~~~~~~~~~

src/index.ts:102:13 - error TS2709: Cannot use namespace 'EventEmitter' as a type.

102   eventHub: EventEmitter
                ~~~~~~~~~~~~


Found 3 errors.

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
Command: /Users/user/.nvm/versions/node/v14.15.0/bin/node
Arguments: /Users/user/.nvm/versions/node/v14.15.0/lib/node_modules/yarn/lib/cli.js typecheck
Directory: /Users/user/my_project
Output:

info Visit https://yarnpkg.com/en/docs/cli/workspace for documentation about this command.

The source near 28, 30 and 102 lines like

import EventEmitter from "events"

//...

function buildEventHub(
  taskId: number,
  jobs: MyJob[],
  pool: Pool
): EventEmitter {
  const jobIds = jobs.map(({ id }) => id)
  const eventHub = new EventEmitter()

//...

async function send(
  taskId: number,
  jobs: MyJob[],
  eventHub: EventEmitter
): Promise<void> {
  const body: RawRequestParams = {
    taskId,
    urls: jobs.map(({ canonicalUrl }) => canonicalUrl)
  }

Why the error occurred?

Upvotes: 3

Views: 911

Answers (1)

Paul F. Wood
Paul F. Wood

Reputation: 1775

The solution is to wrap the EventEmitter in brackets:

import { EventEmitter } from "events"

Instead of this:

import EventEmitter from "events"

Upvotes: 4

Related Questions