hperrin / svelte-material-ui

Svelte Material UI Components
https://sveltematerialui.com/
Apache License 2.0
3.32k stars 285 forks source link

[@smui/common] TypeError for projects with `exactOptionalPropertyTypes: true` #664

Open marekdedic opened 2 months ago

marekdedic commented 2 months ago

Describe the bug Hello, I have a TS project using SMUI and I want to turn on the exactOptionalPropertyTypes tsconfig option. The trouble is, since SMUI distributes TS source files, those get checked by the TS compiler as well, so the extra check gets applied to them as well... and it fails.

I would like to stress that this is not a false positive - the extra check uncovers what is really a potential issue in @smui/common. See the following line:

https://github.com/hperrin/svelte-material-ui/blob/19ea8edba225a22fbfbeeb76030a0d0f9ee1f8e5/packages/common/src/internal/dispatch.ts#L15-L18

Here the new CustomEvent infers its T type from the type of the detail property - which with the extra check is more strictly inferred as T | undefined - this is IMHO correct, because the property is marked as optional in the function signature...

To Reproduce Steps to reproduce the behavior:

  1. Use @smui/common in a project (install it from NPM)
  2. Turn on exactOptionalPropertyTypes

Expected behavior No error

Actual behavior

/home/user/project/node_modules/@smui/common/src/internal/dispatch.ts:15:9
Error: Type 'CustomEvent<T | undefined>' is not assignable to type 'CustomEvent<T>'.
  Type 'T | undefined' is not assignable to type 'T'.
    'T | undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.
      Type 'undefined' is not assignable to type 'T'.
        'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.
  }
  const event: CustomEvent<T> = new CustomEvent(eventType, {
    ...eventInit,

/home/user/project/node_modules/@smui/common/src/internal/dispatch.ts:21:11
Error: Type 'CustomEvent<T | undefined>' is not assignable to type 'CustomEvent<T>'.
  if (duplicateEventForMDC && eventType.startsWith('SMUI')) {
    const duplicateEvent: CustomEvent<T> = new CustomEvent(
      eventType.replace(/^SMUI/g, () => 'MDC'),

Desktop (please complete the following information):

marekdedic commented 2 months ago

I tried fixing it, an easy fix would be to replace T with T | undefined i these two lines:

https://github.com/hperrin/svelte-material-ui/blob/19ea8edba225a22fbfbeeb76030a0d0f9ee1f8e5/packages/common/src/internal/dispatch.ts#L15

https://github.com/hperrin/svelte-material-ui/blob/19ea8edba225a22fbfbeeb76030a0d0f9ee1f8e5/packages/common/src/internal/dispatch.ts#L21