How (and why) to use TypeScript with Svelte, with examples

Published on July 2, 2024

How (and why) to use TypeScript with Svelte, with examples

Svelte is a component-based JavaScript framework for building user interfaces for websites, mobile apps, and other front ends. Svelte is popular due to its light weight and performance, helped by its small bundle size and lack of a virtual DOM. For those who want a full application framework, SvelteKit is also available, providing state management and routing, among other features for rapid app development. Both support TypeScript, so how can you best leverage it?

This article explains how adopting TypeScript enhances your development experience with Svelte (including improving efficiency and app reliability), and provides examples on how to use TypeScript in new and existing Svelte projects.

Why use TypeScript with Svelte/SvelteKit?

Svelte (and SvelteKit) are popular due to the advantages they bring to developers:

  • Reactive, responsive apps: Like React, Svelte lets you create truly interactive web interactions that update the DOM to create animated, dynamic front ends. Your apps can load data as it is required, immediately updating changes to app data in the view, further improving performance and allowing for the seamless loading of remote assets.

  • Performance and optimization: Compiled Svelte apps are highly optimized for performance. This means smaller download sizes and less work for your users' web browsers to do when they execute your compiled code, and improved, fluid user experiences.

  • Familiar syntax with no boilerplate: Svelte apps are written in the JavaScript (or TypeScript), CSS, and HTML syntax that you are already familiar with, and their component architecture reduces the amount of code you need to write by removing boilerplate.

TypeScript further enhances these advantages by making sure your applications are type safe, reducing debugging time and decreasing run-time errors, especially when dealing with dynamically loaded data. Encouraging you to declare variable types also makes the intention of your code clear, resulting in a codebase that’s easier to understand and maintain.

Beyond improvements to debugging and ensuring errors do not make it to production, TypeScript's development tools also streamline development using Svelte libraries, with powerful autocomplete and linting available in most popular IDEs like Visual Studio Code.

TypeScript is, in many ways, the present and future of JS development — so if you haven't begun your TypeScript journey, you should check out the TypeScript handbook, which explains everything you need to know to get up and running.

How to use TypeScript in your next Svelte/SvelteKit project (code example)

Svelte and SvelteKit are built on TypeScript, so their frameworks and modules already provide type information and support linting and code completion. All you need to do is create a SvelteKit project and start writing your own TypeScript in a supported IDE. To create a new SvelteKit project, run the following npm command in your terminal (replacing my-app with the name of your project):

npm create svelte@latest my-app

SvelteKit will then ask you a few questions to get your project set up for you. It will prompt you to select from the list of available app templates (this example uses the "SvelteKit demo app" template), which are helpful if you want to avoid writing a lot of boilerplate from scratch. Importantly, it will also ask you whether you want to add type checking with TypeScript. Make sure you select the option "Yes, using TypeScript syntax" to enable this.

You can then select some additional options — we recommend installing ESLint if you use Visual Studio Code or plan to have CI/CD integrations that automate checking your code for errors.

SvelteKit will then build your project, and you'll see a friendly success message. To start working on your Svelte/TypeScript app, navigate into the newly created project directory and install the npm dependencies by running:

npm install

You can launch your app by running npm run dev and then access your app at http://localhost:5173. Now you're ready to create Svelte components in TypeScript.

Below is an example Svelte/TypeScript component that displays a simple shopping list with a counter next to each item. Create the following component in src/ShoppingList.svelte:

Then, to use your component, add it to an existing page. For example, if you're using the default demo app template as set up by the create svelte command above, you can add it to the main page at src/routes/+page.svelte by importing the component and then adding it at the end of the <section> block, beneath the <counter /> component:

Note the use of globalThis in this example. In Node.js environments, the window variable is not available, so it's best to use globalThis to store data in the global object. In a real application, you'd access your data via a Svelte store (for local data) or a REST or GraphQL API. This is an example of why the type checks are so important — if another component or module provides data to your functions in an unexpected format, you can promptly identify and fix the error.

It's also worth pointing out that you can switch the Svelte documentation to use TypeScript examples instead of JavaScript by toggling the option in the documentation navigation menu.

How to add TypeScript to existing Svelte projects

If you're bootstrapping a new Svelte app, we recommend using the create svelte npm command to create a SvelteKit project. This way, all of the Svelte and TypeScript compilation tools are already set up for you, and you can start writing type-safe and well structured TypeScript code right out of the gate. You'll also have access to the SvelteKit CLI, which takes care of building and previewing your app. 

If you do have an existing Svelte project written in JavaScript and want to start using TypeScript instead, update your existing components and add lang="ts" to their script tags:

You'll also need to rename any JavaScript files that you convert to TypeScript to use the .ts file extension.

If you're migrating from an older version of Svelte that pre-dates built-in TypeScript support and SvelteKit (usually projects started prior to 2020), you'll need to follow some additional steps to set up a TypeScript environment and add type support to your project.

If you're migrating from an older framework version, depending on the complexity of your project (and how many dependency issues you run into while refactoring) you may consider creating a new Svelte project from scratch, and moving your files into it, optionally refactoring as you go. 

Because TypeScript compiles down to regular JavaScript along with the rest of your Svelte app when you build it, your existing JavaScript code will work alongside new and refactored TypeScript code (or you can do it later; the great thing about TypeScript is it compiles to JavaScript, so your existing JavaScript will keep working while you make the transition).

TypeScript best practices In Svelte

If you use Visual Studio Code, you should install the Svelte VS Code extension — it provides syntax highlighting and rich IntelliSense features including diagnostic messages, code autocompletion, and the ability to preview your app.

Visual Code Studio

You can also use svelte-check for diagnostics from the command line (or your CI/CD pipelines).

You should also make sure you're taking full advantage of the features TypeScript brings to Svelte by learning and implementing TypeScript’s developer-centric features, for example:

  • Interfaces: Define the shape of your data using interfaces and types so that non-conforming data is flagged with compile-time errors. This will allow for thorough type safety.

  • Types in variable declarations: Specify the type of variables as well as function parameters and return types. This will make the purpose of your code clearer, and also allow your IDE to provide autocomplete when you use your function.

  • DefinitelyTyped type definitions for npm packages: If you rely on an npm package that doesn't include TypeScript support, DefinitelyTyped may be able to provide community-supplied definitions that you can use for full type checking across your project. 

  • DRY principles: Svelte components and TypeScript's modules allow you to split your code into organized, reusable files. Make sure you take advantage of this so that you can reuse code wherever possible (and do less work).

Flagging a bug in TypeScript

If you are working with data from a GraphQL API, KitQL is a fantastic GraphQL client for SvelteKit that generates typed GraphQL queries. You can also check out the Contentful GraphQL Playground if you'd prefer an online tool for building and testing GraphQL requests.

Rapid, extensible front-end development deserves a composable back end

As Svelte and SvelteKit are developed in TypeScript, it makes sense for developers to build their apps in TypeScript and take full advantage of the type safety and debugging features it offers. You can extend these advantages to your back end too, by utilizing platforms that support GraphQL for type-safe queries and API calls, further improving the reliability and fluidity of your mobile apps and websites.

If you're deploying content like video, images, text, and audio, you can skip back-end development entirely with the Contentful Composable Content Platform, which provides a flexible content management platform that lets you define your content, manage it across your organization, and finally deploy it to your apps, websites, and other digital channels.

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

Guides

Snake Charmer’s Secret: Metaprogramming the Python SDK

March 17, 2017

Websites still play a key role in meeting customer expectations. Read on for tips to modernize your brand’s web strategies and deliver great experiences.
Guides

Modernize your web strategy and deliver customer-winning experiences

January 11, 2024

Learn more about React and React Native and their differences, with context and information so that you can decide which to use for a particular project.
Guides

React vs. React Native: The difference, and which is best for you

October 2, 2024

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started