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: [
       * Auto preprocess supported languages with
       * '<template>'/'external src files' support
      preprocess: autoPreprocess({ /* options available */ })
     * In case you want to use TypeScript outside of Svelte files, too

Then you can write your Svelte components with TypeScript:

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

More information from community blogposts: