deno_std icon indicating copy to clipboard operation
deno_std copied to clipboard

node/EventEmitter - Allow passing a type to define event data

Open Danielduel opened this issue 2 years ago • 0 comments

EventEmitter uses ...args: any[] as event data and string as event names, which is very broad definition. At the same time it doesn't provide any way to narrow down what events developer expect to be part of implementation.

Workaround would be extending EventEmitter as and then defining overloads to use generic type as event definition. https://github.com/ryo-ma/deno-websocket/blob/9e52a3fd659cf8b86f431de5a4d488d9d4632075/lib/websocket.ts#L26 I think there is no big downside to that, but it is generally time consuming and feels redundant to do.

I think we can modify .d.ts file of EventEmitter like I've started doing it here: https://github.com/denoland/deno_std/pull/2111/files#diff-e7d22bd5877f014a874833c7197eaffd5a0e9724eb3f47de0fc404de5b8ff14bR248-R251 The downside of this approach is harder overriding - overriding generic members generates more boilerplate. The solution to simple overriding is what I've done for emit, but it makes event names to be string (instead of keyof) before it can narrow it down to specific event (because wider overload option).

Another option would be defining GenericEventEmitter as separate export (simmilar to what I've shown in the deno-websocket repo, I generally think it is a good approach, the problem is that I feel it should be provided as a standard way when we work with typescript)

My expectation would be to let EventEmitter work as it does right now by default, but allow passing an optional type which tells type guards (and IDE) what to expect (like i've shown in the test): https://github.com/denoland/deno_std/pull/2111/files#diff-e03f76ef798baccc36a2d182d5a954a6567fb7a18c9707a9cc8763c360759fe5R10 (this test fails with typecheck errors, it doesn''t "expect" anything in traditional(?) way)

Danielduel avatar Apr 15 '22 19:04 Danielduel