typescripteslintsvelte

Typescript not parsed in Svelte html section


I'm working on a Svelte project, configured to use typescript.

For every element in the datesToShow array, a div should appear in the DOM. This is done with the code shown bellow.

{#each datesToShow as date}
   <div on:click={() => { changeFocusDate(date) }}> ... </div>
{/each}

When clicking this div, a function, changeFocusDate should be called and the array element corresponding to this div should be passed.

This all works great. I'm however using typescript with explicit-function-return-type enabled, so eslint warns me that my function does not define a return type, which is great. The code does run. When changing it to (): void => { changeFocusDate(date) }, i get:

Unexpected token ParseError

It does not seem to understand the colon. The code doesn't run either.

What's going on here? Eslint parses my code as typescript when I forget to declare the type, but it doesn't when I do declare the type. I only encounter this problem in the html of my Svelte files. The typescript inside the <script> tag performs well (with lang="ts" of course). I'd like to use proper TS inline.

How could this be fixed? I don't think I can move the declaration of the function to the <script> tag, as I have to pass date.


Solution

  • In Svelte 5, it's possible to use TS type annotations inside Svelte markup.

    In Svelte 3 and 4, it is not. To still make ESLint happy, you can create a function which returns a function and invoke that.

    <script lang="ts">
        // ...
        
        function createChangeFocusDateFn(date): () => void {
            return (): void => changeFocusDate(date)
        }
    </script>
    
    {#each datesToShow as date}
       <div on:click={createChangeFocusDateFn(date)}> ... </div>
    {/each}