Search code examples
typescriptsvelte

Svelte TypeScript: Unexpected token when adding type to an event handler


I'm trying to implement TypeScript into Svelte and has a problem like this: when I try to add type to an event in beneath line:

on:click={(e: Event) => onClick(e, data)}

it yells about:

Error: ParseError: Unexpected token

If I remove typing it says that:

Parameter 'e' implicitly has an 'any' type.

How can I add type to this kind of things without an error in Svelte?

EDIT: More complex example:

{#each elementsArray as element}
      <CustomComponent
        on:itemClick={(e: Event) => doSomething(e, element)}>
      </CustomComponent>
    {/each}

Solution

  • According to the official docs, there's no official support for TypeScript in the template.

    At the moment, you cannot [use Typescript inside the template/mustache tags]. Only script/style tags are preprocessed/transpiled.

    You need to move the typecasting to the <script> tag.

    <script lang="ts">
      function onClick(e: MouseEvent) { ... }
    </script>
    <button on:click={onClick}></button>
    

    In case your event is coming as a custom event from a child using createEventDispatcher, your e event will be typed as CustomEvent<any> and you can typecast it in the <script> as you please.

    <script lang="ts">
      let elems = [1,2,3];
      
      function onClick(e: CustomEvent<{foo: string}>, el: number) {
        console.log(e.detail.name);
      }
    <script>
    {#each elems as el}
      <CustomComponent on:itemClick={e => onClick(e, el)}></CustomComponent>
    {/each}
    

    In case you still get errors for implicit any, try turning off noImplicitAny in your tsconfig.json.