[@types/node] events: Strong types for EventEmitter events #55298
-
|
I'm not sure if this has been discussed anywhere on this repo in the past or not - I tried searching for related issues, but didn't really find anything, so apologies if this has already been discussed. I'm wondering if it would be possible to add an optional type parameter to the Node interface MyEvents {
foo: [string, number];
bar: [boolean];
}
const myEventEmitter = new EventEmitter<MyEvents>();
myEventEmitter.on('bar', eventValue => {
// eventValue is a boolean
});
// @ts-expect-error - ['foo', false] not assignable to ['foo', string, number] | ['bar', boolean]
myEventEmitter.emit('foo', false);I've seen similar patterns being used by other projects, using either subclasses of interface Events<E extends {[eventName in keyof E]: any[]}> {
on<K extends keyof E>(eventName: K, listener: (...args: E[K]) => void): this;
emit<K extends keyof E>(eventName: K, ...args: E[K]): boolean;
// other EventEmitter methods you care about...
}
const myEventEmitter = new EventEmitter() as Events<MyEvents>;One concern I have is that event emitters aren't actually limited to emitting known event names. Projects with strongly-typed events often type their emitters in such a way that using an unrecognized event is disallowed, which prevents typo issues, but others are fine with the user emitting custom events on their listeners. Can this be designed to allow typings authors that choice? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
|
Thanks for the discussion about "node", some useful links for everyone: Pinging the DT module owners: @microsoft, @DefinitelyTyped, @jkomyno, @alvis, @r3nya, @btoueg, @smac89, @Touffy, @DeividasBakanas, @eyqs, @Hannes-Magnusson-CK, @hoo29, @kjin, @ajafff, @islishude, @mwiktorczyk, @mohsen1, @n-e, @galkin, @parambirs, @eps1lon, @SimonSchick, @ThomasdenH, @WilcoBakker, @wwwy3y3, @samuela, @kuehlein, @bhongy, @chyzwar, @trivikr, @yoursunny, @qwelias, @ExE-Boss, @Ryan-Willpower, @peterblazejewicz, @addaleax, @victorperin, @ZYSzys, @nodejs, @LinusU, @wafuwafu13. |
Beta Was this translation helpful? Give feedback.
-
|
There are 2 issues:
I've tried a couple times to implement generic EventEmitters but it never quite worked out. |
Beta Was this translation helpful? Give feedback.
See #68313.