Using TypeScript with Svelte

It is a common misconception that Svelte doesn’t work with TypeScript. Svelte is, of course, written in TypeScript, so the project strongly believes in the value of typing. An offical blog post announced full support for it in mid 2020. Here is how to get started:

First you need to change you build setup. We recommend using svelte-preprocess, which will preprocess TypeScript and many more languages out of the box.

Example using svelte-preprocess:

// rollup.config.js
import svelte from 'rollup-plugin-svelte';
import autoPreprocess from 'svelte-preprocess'
import typescript from '@rollup/plugin-typescript';

export default {
  ...,
  plugins: [
    svelte({
      /**
       * Auto preprocess supported languages with
       * '<template>'/'external src files' support
       **/
      preprocess: autoPreprocess({ /* options available https://github.com/sveltejs/svelte-preprocess/blob/master/docs/preprocessing.md */ })
    }),
    /**
     * In case you want to use TypeScript outside of Svelte files, too
     */
    typescript()
  ]
}

Then you can write your Svelte components with TypeScript:

<script lang="ts">
	// Compatible with Svelte v3...
	export const hello: string = 'world';
</script>

<template>
	<div>Hello {hello}</div>
</template>

More information from community blogposts:

Published:
Last update: