Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 35 ยท Quality

TypeScript in Svelte

Use TypeScript in Svelte 5 - lang="ts", typed $props, $state generics, Snippet and event types, generic components, .svelte.ts modules and svelte-check.

TypeScript catches mistakes before your users do: a misspelled prop, a null you forgot to handle, a function called with the wrong arguments. Svelte 5 has first-class TypeScript support. You add lang="ts" to a script tag and write types the way you would in any other file; the editor and svelte-check do the rest.

The compiler and TypeScript toolchain for Svelte cannot run on this site, so Svelte code is read-only. The <TryIt> blocks use plain JavaScript to model runtime validation, which complements types (types vanish at runtime).

Turning it on

New projects from npx sv create can include TypeScript. Existing ones need lang="ts" on scripts:

HTML
<script lang="ts">
  let count: number = $state(0);
  let name = $state('Ada'); // inferred as string
</script>

Type annotations are erased by the build. Svelte 5 understands type-only syntax directly; features that need real code transformation (enums, namespaces, parameter properties) require the Vite preprocessor (vitePreprocess) that SvelteKit templates include. Prefer plain unions over enums anyway.

Type annotations appear only in the script. Markup expressions stay plain JavaScript, so {value as string} in a template is not allowed; compute typed values in the script.

Typing props

Props come from $props(). Annotate the destructuring or declare an interface:

HTML
<script lang="ts">
  interface Props {
    title: string;
    count?: number;                       // optional
    variant?: 'primary' | 'danger';       // union of literals
    onselect?: (id: number) => void;      // callback prop
  }

  let { title, count = 0, variant = 'primary', onselect }: Props = $props();
</script>

<button class={variant} onclick={() => onselect?.(count)}>{title}</button>

With Props in place, <Button title={5} /> or <Button variant="loud" /> is an editor error. Callback props (named onselect) replace the Svelte 4 createEventDispatcher.

Spreading HTML attributes

To make a wrapper component accept everything a <button> accepts, extend the DOM types:

HTML
<script lang="ts">
  import type { HTMLButtonAttributes } from 'svelte/elements';

  interface Props extends HTMLButtonAttributes {
    loading?: boolean;
  }

  let { loading = false, children, ...rest }: Props = $props();
</script>

<button {...rest} disabled={loading || rest.disabled}>
  {@render children?.()}
</button>

svelte/elements has types for every HTML element (HTMLInputAttributes, HTMLAnchorAttributes...), including children.

Typing state, derived and bindable values

HTML
<script lang="ts">
  interface Todo { id: number; text: string; done: boolean }

  let todos = $state<Todo[]>([]);              // empty array needs a type
  let selected = $state<Todo | null>(null);    // starts as null
  const remaining = $derived(todos.filter((t) => !t.done).length); // inferred number

  let { value = $bindable('') }: { value?: string } = $props();
</script>

When the initial value does not tell TypeScript the full type (an empty array, null), pass it as the generic: $state<Todo[]>([]).

Snippets and children

A children prop or any snippet prop has the type Snippet, optionally with parameters:

HTML
<script lang="ts">
  import type { Snippet } from 'svelte';

  interface Props<T> {
    items: T[];
    row: Snippet<[T, number]>;     // receives item and index
    empty?: Snippet;
  }

  let { items, row, empty }: Props<any> = $props();
</script>

Generic components

Use the generics attribute on the script tag to make a component generic. TypeScript then infers T from the props you pass:

HTML
<!-- List.svelte -->
<script lang="ts" generics="T extends { id: number | string }">
  import type { Snippet } from 'svelte';

  let { items, row }: { items: T[]; row: Snippet<[T]> } = $props();
</script>

<ul>
  {#each items as item (item.id)}
    <li>{@render row(item)}</li>
  {/each}
</ul>
HTML
<List items={users}>
  {#snippet row(user)}   <!-- user is typed as the element type of users -->
    {user.name}
  {/snippet}
</List>

Types for events and elements

DOM events are typed by the handler attribute, so inline handlers are inferred. For separate functions, annotate the event:

HTML
<script lang="ts">
  function onInput(e: Event & { currentTarget: HTMLInputElement }) {
    query = e.currentTarget.value;
  }

  let canvas: HTMLCanvasElement | undefined = $state();
</script>

<input oninput={onInput} />
<canvas bind:this={canvas}></canvas>

Use currentTarget (the element the handler is on) rather than target (which could be a child), so you avoid casts. bind:this variables start undefined, so include it in the type.

Rune modules in .svelte.ts

Shared logic goes in .svelte.ts files and can be fully typed:

TypeScript
// src/lib/cart.svelte.ts
export interface Item { id: number; name: string; price: number; qty: number }

class Cart {
  items = $state<Item[]>([]);
  total = $derived(this.items.reduce((s, i) => s + i.price * i.qty, 0));

  add(item: Omit<Item, 'qty'>) {
    const found = this.items.find((i) => i.id === item.id);
    if (found) found.qty++;
    else this.items.push({ ...item, qty: 1 });
  }
}

export const cart = new Cart();

SvelteKit types

SvelteKit generates types per route into ./$types:

TypeScript
// +page.server.ts
import type { PageServerLoad, Actions } from './$types';

export const load: PageServerLoad = async ({ params }) => ({ post: await getPost(params.slug) });
HTML
<script lang="ts">
  import type { PageProps } from './$types';
  let { data, form }: PageProps = $props();   // data.post is fully typed
</script>

The return type of load flows to data automatically: change the server code and the page reports the error. Augment App.Locals, App.Error and App.PageData in src/app.d.ts for your own shapes.

Types vanish at runtime

TypeScript does not check data that arrives from a form, a URL or an API: it only checks your code. Validate untrusted data at the boundary, for example with a schema library or a small guard, and let types describe the validated result.

JS A runtime guard that narrows unknown data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Checking the project

npx svelte-check type-checks .svelte, .ts and .svelte.ts files and prints compiler warnings too. Add it to package.json as "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json" and run it in CI with your tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you type props in Svelte 5?

    In runes mode props come from $props(); annotate the destructured result (inline or with an interface).
  2. 2. Why write $state<Todo[]>([])?

    An empty array would infer never[] or any[]; the generic states the intended type.
  3. 3. What type does a children prop have?

    Snippets, including children, are typed with Snippet from 'svelte'; parameters go in a tuple: Snippet<[Item]>.
  4. 4. Does TypeScript validate JSON returned from an API at runtime?

    Types exist only at compile time. Use runtime validation at the boundaries.

Summary

  • Add lang="ts"; type props via $props() with an interface; use Snippet for children and generics for generic components.
  • Give $state a generic when the initial value is ambiguous; use .svelte.ts for typed reactive modules.
  • SvelteKit generates ./$types so data, form and load stay in sync.
  • Types disappear at runtime: validate untrusted input, and run svelte-check in CI.

Next: Project: Todo App