Basic Setup
Using <script lang="ts">
To use TypeScript in your Svelte components, add the lang="ts" attribute to your script tags:
Only type-only features are supported out of the box. Features that require TypeScript to output code (like enums or decorator metadata) need a preprocessor.
Type-Only Features Supported
Svelte’s built-in TypeScript support includes:- Type annotations
- Interface declarations
- Type assertions
- Generic types
- Type imports/exports
Features Requiring a Preprocessor
The following TypeScript features require a preprocessor setup:- Enums
- Parameter properties (
private,protected,publicmodifiers in constructors) - Features not yet in ECMAScript Stage 4
Preprocessor Configuration
Using Vite or SvelteKit
For full TypeScript support, configurevitePreprocess in your svelte.config.js:
svelte.config.js
1
npx sv createOther Build Tools
For Rollup or Webpack:-
Install dependencies:
- Configure the preprocessor in your bundler plugin configuration
TypeScript Configuration
Required tsconfig.json Settings
Ensure yourtsconfig.json includes these critical settings:
tsconfig.json
- target: Use at least
ES2015so classes aren’t transpiled to functions - verbatimModuleSyntax: Keeps import/export statements as-is
- isolatedModules: Ensures each file can be compiled independently (required for Vite)
Typing Components
Typing $props
Define props using TypeScript interfaces:
Generic Components
Create components with generic type relationships using thegenerics attribute:
generics attribute accepts the same syntax as TypeScript generic parameters:
- Multiple generics:
generics="T, U" - Constraints:
generics="T extends string" - Defaults:
generics="T = string"
Typing Wrapper Components
For components that wrap native elements, use types fromsvelte/elements:
Typing State and Derived Values
Typing $state
Type state variables like regular TypeScript variables:
undefined:
Typing $derived
Derived values infer their type from the expression:
Component Type Utilities
The Component Type
Use the Component type to constrain dynamic components:
Extracting Component Props
UseComponentProps to get a component’s prop types:
Component Constructor and Instance Types
Extending DOM Types
For custom or experimental attributes, augment thesvelte/elements module:
additional-svelte-typings.d.ts
IDE Support
VS Code Extension
Install the Svelte for VS Code extension for:- TypeScript error checking in your editor
- Autocompletion for Svelte syntax
- Type information on hover
- Automatic imports
Command Line Checking
Usesvelte-check for CI/CD integration:
Best Practices
1
"strict": true in tsconfig.json for maximum type safetyany - Use unknown and type guards instead of bypassing type checking