TypeScript-DOM-lib-generator icon indicating copy to clipboard operation
TypeScript-DOM-lib-generator copied to clipboard

fix: updated CustomEvent.detail to be null when not defined

Open GauBen opened this issue 2 years ago • 9 comments

Fixes #1585

GauBen avatar Jun 29 '23 07:06 GauBen

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.

github-actions[bot] avatar Jun 29 '23 07:06 github-actions[bot]

I'll update the tests accordingly if this change is accepted

GauBen avatar Jun 29 '23 08:06 GauBen

Sounds fine to me.

saschanaz avatar Jun 29 '23 09:06 saschanaz

Can you perhaps also add unit tests for this?

saschanaz avatar Jun 29 '23 19:06 saschanaz

Is eventlistener.ts the right place for it?

GauBen avatar Jun 29 '23 20:06 GauBen

I'd prefer a separate file for custom events.

saschanaz avatar Jun 29 '23 20:06 saschanaz

I just noticed that it is possible to create broken CustomEvents: https://www.typescriptlang.org/play?#code/MYewdgziA2CmB00QHMAUZYHcAEBhArhAC4gC2AogG6xhEA8xATgJZjIB8qA5LNbVwEp4AE1hEAhs2jYAvHOxh80aAIDcAKAD0m7Lr36Dho8aMA9APxA

Do I try to address this too? Would this be a breaking change?

Edit, suggested change:

type CustomEventInit<T = any> = EventInit & (T extends {} ? { detail: T } : { detail?: T });

declare var CustomEvent: {
  prototype: CustomEvent;
  new <T>(
    ...args: T extends {}
      ? [type: string, eventInitDict: CustomEventInit<T>]
      : [type: string, eventInitDict?: CustomEventInit<T>]
  ): CustomEvent<T>;
};

GauBen avatar Jun 29 '23 20:06 GauBen

Looks right, although it starts to be over-complex... I'm okay with that if @sandersn says okay

saschanaz avatar Jul 12 '23 19:07 saschanaz

I don't know CustomEvent, but running the example from the playground link, it looks like CustomEvent.default is null if CustomEventInit isn't provided to the constructor. At least, it doesn't appear to be undefined the way that { detail?: T } implies. So what about this?

interface CustomEventInit<T = any> extends EventInit {
    detail: T; // note: you probably need to add the `T extends {} ? T : null` conditional type to map undefined -> null
}

declare var CustomEvent: {
  prototype: CustomEvent;
  new<T>(type: string, eventInitDict: CustomEventInit<T>): CustomEvent<T>
  new(type: string): CustomEvent<null>
};

Of course this might break backward compatibility. I don't know how new or widely-used CustomEvent is.

sandersn avatar Jul 13 '23 23:07 sandersn