Declaring events in a TypeScript class which extends EventEmitter

前端 未结 4 1498
有刺的猬
有刺的猬 2021-01-01 11:20

I have a class extends EventEmitter that can emit event hello. How can I declare the on method with specific event name and listener s

4条回答
  •  無奈伤痛
    2021-01-01 11:54

    Most usable way of doing this, is to use 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);
        }
    }
    

    Note that if you are exporting your class, both the interface and class have to be declared with the export keyword.

提交回复
热议问题