eds1999
eds1999

Reputation: 1058

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.

Upvotes: 1

Views: 1625

Answers (3)

dummdidumm
dummdidumm

Reputation: 5436

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}

Upvotes: 4

Astro Bear
Astro Bear

Reputation: 81

Support for TypeScript in Svelte markup is now coming in Svelte 5. See here

Upvotes: 1

AlexRMU
AlexRMU

Reputation: 67

Also, if you want to use local variables and passed arguments, you can use //@ts-ignore

{#each options as option}
    <div
        on:change={
        //@ts-ignore
        e => change_event(e, option)
        }
    />
{/each}

Upvotes: 1

Related Questions