Last active
July 26, 2023 17:12
-
-
Save barfi/a173f70604b1b95ed75fa0ea52c5cf19 to your computer and use it in GitHub Desktop.
Revisions
-
barfi revised this gist
Jul 26, 2023 . 1 changed file with 9 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -4,7 +4,7 @@ type CustomEmitterEvents = { eventA: (payload: number) => void eventB: (payload: string) => void eventC: (arg: boolean, msg: string) => void } // Interface of your sublcass, matches the EventEmitter method signatures @@ -26,7 +26,13 @@ interface CustomEmitter { class SuperEmitter extends EventEmitter implements CustomEmitter { // Override parent class on method override on<T extends keyof CustomEmitterEvents>(event: T, listener: CustomEmitterEvents[T]): this { super.on(event, listener) return this } // other stuff... } @@ -39,7 +45,7 @@ emitter.on('eventA', (payload: number) => { }) emitter.on('eventC', (arg: boolean, msg: string) => { // your stuff... }) ``` -
barfi created this gist
Jul 26, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,47 @@ ```ts // Map all your event names with their handlers type CustomEmitterEvents = { eventA: (payload: number) => void eventB: (payload: string) => void eventC: (arg: boolean, msg: string) => boolean } // Interface of your sublcass, matches the EventEmitter method signatures interface CustomEmitter { // Matches EventEmitter.on on<T extends keyof CustomEmitterEvents>(event: T, listener: CustomEmitterEvents[T]): this // Matches EventEmitter.off off<T extends keyof CustomEmitterEvents>(event: T, listener: CustomEmitterEvents[T]): this // Matches EventEmitter.emit emit<T extends keyof CustomEmitterEvents>(event: T, ...args: Parameter<CustomEmitterEvents[T]>: boolean } // Define your subclass class SuperEmitter extends EventEmitter implements CustomEmitter { // your stuff... } // You can use it like below const emitter = new SuperEmitter() emitter.on('eventA', (payload: number) => { // your stuff... }) emitter.on('eventC', (arg: boolean, msg: string) => { // your stuff... }) ``` THX to [BRIAN MANCINI](https://www.derpturkey.com/typescript-and-node-js-eventemitter/) for his idea.