Home > Software design >  How to declare a subclass of EventEmitter?
How to declare a subclass of EventEmitter?

Time:02-05

I am writing type definitions for JS code in types.d.ts and I want to declare a class that subclasses EventEmitter, but it won't let me:

type EventEmitter = import('events').EventEmitter

// 'EventEmitter' only refers to a type, but is being used as a value here.ts(2693)
declare class Foo extends EventEmitter {}

How can I do this?

UPDATE: As a workaround, I copied the nodejs.eventemitter interface definition into my types.d.ts, and changed interface to declare class, and it works. Is this a bug in the NodeJS typing?

CodePudding user response:

[Edit] Changing the import I don't get an error

import type {EventEmitter} from 'events'

declare class Foo extends EventEmitter {}

Playground

CodePudding user response:

I came up with this workaround:

// Aclass is `class` but A is `type`
type A = import('./a-class').AClass

// @ts-ignore -- complains that A methods aren't implemented
declare class AC implements A {}

declare class B extends AC {
}

it complains on the AC declaration so I have to ignore it.

  •  Tags:  
  • Related