在扩展EventEmitter的TypeScript类中声明事件

我有一个类扩展EventEmitter ,可以发出事件hello 。 我怎样才能声明特定的事件名称和侦听器签名的方法?

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

如果您想查看特定事件名称的types,据我所知,您只能使用如下界面:

 interface IMyEvent { on(event: 'hello', listener: (name: string) => void): this; on(event: string, listener: Function): this; } class MyClass extends events.EventEmitter implements IMyEvent{ emitHello(name: string): void { this.emit('hello', name); } } 

有了这样的声明,当你使用IMyEventtypes的variables时,在input.on()函数时会有一个types化的intellisensebuild议

更新1

第二种方法做到这一点,我认为更有用的是使用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); } } 

只需将它自己连接到on('hello'例如:

 class MyClass extends events.EventEmitter { emitHello(name: string): void { this.emit('hello', name); } on(listener: (name: string) => void){ return this.on('hello',listener); } }