Skip to content

Typescript createEventDispatcher does not propagate event types correctly #1388

@aliak00

Description

@aliak00

Describe the bug

Hey there! I'm seeing some strange behavior in a sveltekit project with typescript enabled when using createEventDispatcher.

The types of a custom event only seem to propagate if they are declared inline when calling createEventDispatcher.

I.e. dispatch1 breaks typings and dispatch2 works great.

import { createEventDispatcher } from 'svelte';
type Events = {
  event1: {
    value: string;
  };
};
const dispatch1 = createEventDispatcher<Events>();
const dispatch2 = createEventDispatcher<{
  event2: {
    value: string;
  };
}>();

There result of using a component that dispatches the above events:

<Component
  on:event1={(e) => {
    // No error because it's typed as any
    console.log(e.detail.gagagaga);
  }}
  on:event2={(e) => {
    // Error because e is correctly typed
    console.log(e.detail.gagagaga);
  }}
/>

Reproduction

https://github.com/aliak00/tmp-sveltekit-custom-event-types

Logs

❯ npm run check

> tmp-sveltekit-custom-event-types@0.0.1 check
> svelte-check --tsconfig ./tsconfig.json


====================================
Loading svelte-check in workspace: ./tmp-sveltekit-custom-event-types
Getting Svelte diagnostics...

./tmp-sveltekit-custom-event-types/src/routes/index.svelte:10:24
Error: Property 'gagagaga' does not exist on type '{ value: string; }'. (js)
	on:event2={(e) => {
		console.log(e.detail.gagagaga);
	}}


====================================
svelte-check found 1 error, 0 warnings, and 0 hints

System Info

System:
    OS: macOS 12.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 2.47 GB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 14.18.2 - ~/.nvm/versions/node/v14.18.2/bin/node
    Yarn: 1.22.17 - /usr/local/bin/yarn
    npm: 8.3.0 - ~/.nvm/versions/node/v14.18.2/bin/npm
  Browsers:
    Chrome: 98.0.4758.80
    Safari: 15.2
  npmPackages:
    @sveltejs/adapter-auto: next => 1.0.0-next.17 
    @sveltejs/kit: next => 1.0.0-next.251 
    svelte: ^3.44.0 => 3.46.3

Severity

serious, but I can work around it

Additional Information

The work around is not using CustomEvent and providing callbacks like export let onEvent: () => void via the component so the typings are correct.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedFixed in master branch. Pending production release.bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions