Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

strictEvents event dispatchers can be called without providing a value when the event key is not optional #1966

Closed
DetachHead opened this issue Mar 27, 2023 · 2 comments
Labels
bug Something isn't working upstream

Comments

@DetachHead
Copy link
Contributor

Describe the bug

if a key in an event dispatcher type is required, it can be dispatched without a value, causing the CustomEvent.detail to be null at runtime when typescript does not say it's nullable

Reproduction

a.svelte

<script lang="ts" strictEvents>
    import { createEventDispatcher } from 'svelte'

    const dispatch = createEventDispatcher<{ a: number }>()
</script>

<button on:click={() => dispatch('a')}>asdf</button>

b.svelte

<script lang="ts" strictEvents>
    import A from './a.svelte'
</script>

<A
    on:a={(e) => {
        // no typescript error, crashes at runtime
        console.log(e.detail.toString())
    }}
/>

Expected behaviour

the function created by createEventDispatcher should require the detail argument when the EventKey type is required.

the updated function signature could look something like this:

type RequiredKeys<T> = Exclude<{
    [K in keyof T]-?: undefined extends T[K] ? never : K;
}[keyof T], keyof {}>

type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>

declare function createEventDispatcher<EventMap extends {} = any>(): {
    <EventKey extends RequiredKeys<EventMap>>(type: EventKey, detail: EventMap[EventKey], options?: DispatchOptions): boolean;
    <EventKey extends OptionalKeys<EventMap>>(type: EventKey, detail?: EventMap[EventKey], options?: DispatchOptions): boolean;
}

playground

System Info

  • OS: windows 10
  • IDE: vscode

Which package is the issue about?

svelte-check

Additional Information, eg. Screenshots

No response

@DetachHead DetachHead added the bug Something isn't working label Mar 27, 2023
@jasonlyu123
Copy link
Member

See upstream PR sveltejs/svelte#7224

@jasonlyu123
Copy link
Member

Fixed in svelte 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working upstream
Projects
None yet
Development

No branches or pull requests

2 participants