microsoft / TypeScript-DOM-lib-generator

Tool for generating dom related TypeScript and JavaScript library files
Apache License 2.0
600 stars 417 forks source link

feat: add type parameter to EventTarget #1712

Open 43081j opened 2 months ago

43081j commented 2 months ago

This introduces a type parameter to EventTarget such that the following is now possible:

interface CustomMap {
  'test-event': CustomEvent<{x: number; y: number}>;
}

declare const customTarget: EventTarget<CustomMap>;

customTarget.addEventListener('test-event', (event) => {
  // event is now `CustomEvent<{x: number; y: number}>`
  event.detail.x;
  event.detail.y;
});

Defaults to T = any to maintain existing behaviour otherwise.

Reviewer notes

i did two attempts at this:

  1. override the interface and just specify each of the signatures (this pr)
  2. update the emitter to have a special case for EventTarget where it will then emit event handlers

1 - overrides (this PR)

i don't like that i'm basically repeating the signatures of emitEventHandlers manually in the overrides JSON. though the result does seem to work well.

maybe there's a cleaner way to do this?

2 - update the emitter

we could just change emitEventHandlers to ultimately do this logic:

      if (hasEventListener || ehParentCount > 1) {
        mapName = `${i.name}EventMap`;
      } else if (ehParentCount === 1) {
        mapName = `${iNameToEhParents[i.name][0].name}EventMap`;
      } else if (i.name === "EventTarget") {
        mapName = "T";

which is then used to print the signatures.

i've tried this and it failed because it adds those signatures rather than replacing the existing ones.

any advice would be helpful of how to approach this

also if there's some fundamental reason this can never work, im of course happy to close the PR but would like to understand first

github-actions[bot] commented 2 months ago

Thanks for the PR!

This section of the codebase is owned by @saschanaz - if they write a comment saying "LGTM" then it will be merged.

saschanaz commented 1 month ago

This sounds nice to me and perhaps we can stop emitting duplicate addEventListeners and migrate to this method.

@sandersn might want to check too.

sandersn commented 1 month ago

How is this different from https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1624 ? My memory is that that (plus previous attempts) was too slow and also likely to cause breaks, but I can't remember if I finished testing the most recent attempt.

43081j commented 1 month ago

@sandersn it seems the other PR is for making events generic such that target can be specified (Event<T>), while this makes EventTarget generic such that addEventListener can be strongly typed

if performance allows, we'd probably want both

whats the best way for me to perf test this?