typed-emitter icon indicating copy to clipboard operation
typed-emitter copied to clipboard

Extending EventEmitter and implementing TypedEventEmitter is broken

Open orgads opened this issue 1 year ago • 5 comments

Hi,

The following example works with typed-emitter v1, but breaks with v2.

import { EventEmitter } from 'events';
import TypedEmitter from 'typed-emitter';

type TestEvents = {
  foo: () => void;
};

export class ITestEventEmitter extends (EventEmitter as new () => TypedEmitter<TestEvents>) { }

export abstract class TestClass extends EventEmitter implements ITestEventEmitter {
}

Error message:

Class 'TestClass' incorrectly implements class 'ITestEventEmitter'. Did you mean to extend 'ITestEventEmitter' and inherit its members as a subclass?
  The types returned by 'rawListeners(...)' are incompatible between these types.
    Type 'Function[]' is not assignable to type 'TestEvents[E][]'.
      Type 'Function' is not assignable to type 'TestEvents[E]'.
        Type 'Function' is not assignable to type '() => void'.
          Type 'Function' provides no match for the signature '(): void'.ts(2720)

My use-case is a class that extends another class, which is an EventEmitter, but needs to also implement typed events.

orgads avatar Nov 13 '23 11:11 orgads

ping

orgads avatar Dec 03 '23 06:12 orgads

ping

Tankonyako avatar Jan 25 '24 11:01 Tankonyako

i found solution,

import EventEmitter from "events";
import TypedEmitter, {EventMap} from "typed-emitter";

export default class TEventEmitter<T extends EventMap> extends (EventEmitter as { new<T extends EventMap>(): TypedEmitter<T> })<T>
{

}

then i use it by

import TEventEmitter from "@/utils/TEventEmitter";

export default class Browser extends TEventEmitter<BrowserEvents> {}

Tankonyako avatar Jan 25 '24 11:01 Tankonyako

Unfortunately, looks like abandoned package.

artsiommiksiuk avatar Apr 15 '24 20:04 artsiommiksiuk

This one works:

https://www.npmjs.com/package/tiny-typed-emitter

artsiommiksiuk avatar Apr 15 '24 20:04 artsiommiksiuk