svelte
svelte copied to clipboard
fix: ensure createEventDispatcher works with types from generics
fixes #8860
This contains a small but unfortunately unavoidable breaking change: If you used never
to type that the second parameter shouldn't be set (which the docs recommended for a short time), then you need to change that to null
:
const dispatch = createEventDispatcher<{
- noParameter: never;
+ noParameter: null;
}>();
Before submitting the PR, please make sure you do the following
- [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [x] Prefix your PR title with
feat:
,fix:
,chore:
, ordocs:
. - [x] This message body should clearly illustrate what problems it solves.
- [x] Ideally, include a test that fails without this PR but passes with it.
Tests and linting
- [x] Run the tests with
pnpm test
and lint the project withpnpm lint
We'll need to do the same for the Action interface 😞 will get to it later
Hey! I observed a few interesting behaviors regarding the new createEventDispatcher
type.
-
This pull request slightly changes the behavior for
null
andundefined
.// Setup const dispatch = createEventDispatcher<{ optional?: number; nullable: number | null; }>();
Before
// Both are ok dispatch('optional'); dispatch('nullable'); // Both are ok dispatch('optional', undefined); dispatch('nullable', undefined); // Inconsistency dispatch('optional', null); // Error dispatch('nullable', null); // Ok
After
// All ok dispatch('optional'); dispatch('nullable'); dispatch('optional', undefined); dispatch('nullable', undefined); dispatch('optional', null); dispatch('nullable', null);
-
As
CustomEvent.detail
defaults tonull
, the inferred types are slightly off when usingundefined
/?:
:const dispatch = createEventDispatcher<{ click: undefined }>(); ```   https://svelte.dev/repl/147bfc07869f4909b34f83951665155b?version=4.0.0 Tracked in https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1585
I thought it was interesting to mention here, as tightening types might be a breaking change
Thanks for testing these out! The new behavior is actually more correct, as undefined
and null
will both result in null
for event.detail
The last insight is actually unrelated, it's how the Svelte language server resolves these types - that hasn't changed, but should probably adjusted to be null
for detail
in that case.