svelte event parameter type for typescript

Viewed 8649

So new to svelte but it is so small it is perfect for a job i am working on.

Went for the typescript option: https://svelte.dev/blog/svelte-and-typescript

How or where can i find the types for custom component events:

A simple login component form:

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

  const dispatch = createEventDispatcher()
  let isSubmitting = false
  const handleSubmit = (e: HTMLFormElement) => {
    e.preventDefault()
    isSubmitting = true
    const payload = {
      username: e.target.username.value,
      password: e.target.password.value,
    }
    dispatch('submit', payload)
  }
</script>

<form on:submit={handleSubmit}>
    <label for="username"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="username" required id="username">

    <label for="password"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="password" required id="password">

    <button type="submit" disabled={isSubmitting}>Login</button>
</form>

Included in another component to handle the submit:

<script lang="ts">
  import Login from './molecules/Login.svelte'
  const loginHandle = function (a: any) {
    console.log(a)
  }
</script>

<main class="{open}">
   {#if !authenticated}
      <Login on:submit={loginHandle}/>
   {/if}
</main>

Right now there is an ugly any added to the loginHandle but when dumping the event to console it looks to be very svelte specific.. where can i find the type?

3 Answers

For full typing, change the event raiser to:

const dispatch = createEventDispatcher<{submit:{username:string, password:string}}>()

And the event consumer to:

const loginHandle = function (a: CustomEvent<{username:string, password:string}>) {
    console.log(a.detail.username) //username is type string
    console.log(a.detail.password) //password is type string
}

This will make dispatch("submit", "wrongDetailType") fail. And it eliminates the a.detail being of type "any" in the handler.

Svelte now ships with a CustomEvent interface definition. So you can declare your function as below.

const loginHandle = function (a: CustomEvent) {
    console.log(a)
}

How or where can i find the types for custom component events:

You can pass an object to the generic of the createEventDispatcher function. Where key is a custom event name and value is a detail object.

Child component (<Calendar />)

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

  const dispatch = createEventDispatcher<{ select: Date }>()

  function onSelect(date: Date): void {
    dispatch('select', date)
  }
</script>

...

Parent component

<script>
  function handleSelect (event: CustomEvent<Date>) {
    console.log('Selected date', event.detail)
  }
</script>

<Calendar on:select={handleSelect} />

Usage example

enter image description here

Related