Svelte logo

Svelte by Example: TypeScript

Since Svelte <script> code is plain JavaScript, Svelte has great TypeScript support.

In this example, we'll review how to use TypeScript with Svelte.

Add lang="ts" to a component's script tag to enable TypeScript.

Props & data are regular variables and can be types as such.

Events are regular HTML events.

A text editor with Svelte support will understand the types in templates.

Todo.svelte

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

  const dispatch = createEventDispatcher();

  export let task: string;
  export let completed: boolean = false;

  function handleInput(event: Event) {
    const target = event.target as HTMLInputElement;

    dispatch('checked', {
      checked: target.checked,
    });
  }
</script>

<p>
  <input
    type="checkbox"
    checked={completed}
    on:input={handleInput}
  >
  {task}
</p>