Skip to main content

svelte

import {
	function afterUpdate(fn: () => void): void

Schedules a callback to run immediately after the component has been updated.

The first time the callback runs will be after the initial onMount.

In runes mode use $effect instead.

afterUpdate
,
function beforeUpdate(fn: () => void): void

Schedules a callback to run immediately before the component is updated after any state change.

The first time the callback runs will be before the initial onMount.

In runes mode use $effect.pre instead.

beforeUpdate
,
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:

const dispatch = createEventDispatcher&#x3C;{
 loaded: never; // does not take a detail argument
 change: string; // takes a detail argument of type string, which is required
 optional: number | null; // takes an optional detail argument of type number
}>();
@deprecatedUse callback props and/or the $host() rune instead — see https://svelte-5-preview.vercel.app/docs/deprecations#createeventdispatcher
createEventDispatcher
,
function createRawSnippet<Params extends unknown[]>(fn: (...params: Getters<Params>) => {
    render: () => string;
    setup?: (element: Element) => void | (() => void);
}): Snippet<Params>

Create a snippet programmatically

createRawSnippet
,
function flushSync(fn?: (() => void) | undefined): void

Synchronously flushes any pending state changes and those that result from it.

flushSync
,
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T

Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.

getAllContexts
,
function getContext<T>(key: any): T

Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.

getContext
,
function hasContext(key: any): boolean

Checks whether a given key has been set in the context of a parent component. Must be called during component initialisation.

hasContext
,
function hydrate<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: {} extends Props ? {
    target: Document | Element | ShadowRoot;
    props?: Props;
    events?: Record<string, (e: any) => any>;
    context?: Map<any, any>;
    intro?: boolean;
    recover?: boolean;
} : {
    target: Document | Element | ShadowRoot;
    props: Props;
    events?: Record<string, (e: any) => any>;
    context?: Map<any, any>;
    intro?: boolean;
    recover?: boolean;
}): Exports

Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component

hydrate
,
function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: {} extends Props ? {
    target: Document | Element | ShadowRoot;
    anchor?: Node;
    props?: Props;
    events?: Record<string, (e: any) => any>;
    context?: Map<any, any>;
    intro?: boolean;
} : {
    target: Document | Element | ShadowRoot;
    props: Props;
    anchor?: Node;
    events?: Record<string, (e: any) => any>;
    context?: Map<any, any>;
    intro?: boolean;
}): Exports

Mounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component. Transitions will play during the initial render unless the intro option is set to false.

mount
,
function onDestroy(fn: () => any): void

Schedules a callback to run immediately before the component is unmounted.

Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.

onDestroy
,
function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside a server-side component.

onMount
,
function setContext<T>(key: any, context: T): T

Associates an arbitrary context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.

Like lifecycle functions, this must be called during component initialisation.

setContext
,
function tick(): Promise<void>

Returns a promise that resolves once any pending state changes have been applied.

tick
,
function unmount(component: Record<string, any>): void

Unmounts a component that was previously mounted using mount or hydrate.

unmount
,
function untrack<T>(fn: () => T): T

Use untrack to prevent something from being treated as an $effect / $derived dependency.

https://svelte-5-preview.vercel.app/docs/functions#untrack

untrack
} from 'svelte';

afterUpdate

Use $effect instead — see https://svelte-5-preview.vercel.app/docs/deprecations#beforeupdate-and-afterupdate

Schedules a callback to run immediately after the component has been updated.

The first time the callback runs will be after the initial onMount.

In runes mode use $effect instead.

function afterUpdate(fn: () => void): void;

beforeUpdate

Use $effect.pre instead — see https://svelte-5-preview.vercel.app/docs/deprecations#beforeupdate-and-afterupdate

Schedules a callback to run immediately before the component is updated after any state change.

The first time the callback runs will be before the initial onMount.

In runes mode use $effect.pre instead.

function beforeUpdate(fn: () => void): void;

createEventDispatcher

Use callback props and/or the $host() rune instead — see https://svelte-5-preview.vercel.app/docs/deprecations#createeventdispatcher

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

The event dispatcher can be typed to narrow the allowed event names and the type of the detail argument:

const const dispatch: anydispatch = createEventDispatcher<{
 loaded: neverloaded: never; // does not take a detail argument
 change: stringchange: string; // takes a detail argument of type string, which is required
 optional: number | nulloptional: number | null; // takes an optional detail argument of type number
}>();
function createEventDispatcher<
	EventMap extends Record<string, any> = any
>(): EventDispatcher<EventMap>;

createRawSnippet

Create a snippet programmatically

function createRawSnippet<Params extends unknown[]>(
	fn: (...params: Getters<Params>) => {
		render: () => string;
		setup?: (element: Element) => void | (() => void);
	}
): Snippet<Params>;

flushSync

Synchronously flushes any pending state changes and those that result from it.

function flushSync(fn?: (() => void) | undefined): void;

getAllContexts

Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.

function getAllContexts<
	T extends Map<any, any> = Map<any, any>
>(): T;

getContext

Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.

function getContext<T>(key: any): T;

hasContext

Checks whether a given key has been set in the context of a parent component. Must be called during component initialisation.

function hasContext(key: any): boolean;

hydrate

Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component

function hydrate<
	Props extends Record<string, any>,
	Exports extends Record<string, any>
>(
	component:
		| ComponentType<SvelteComponent<Props>>
		| Component<Props, Exports, any>,
	options: {} extends Props
		? {
				target: Document | Element | ShadowRoot;
				props?: Props;
				events?: Record<string, (e: any) => any>;
				context?: Map<any, any>;
				intro?: boolean;
				recover?: boolean;
			}
		: {
				target: Document | Element | ShadowRoot;
				props: Props;
				events?: Record<string, (e: any) => any>;
				context?: Map<any, any>;
				intro?: boolean;
				recover?: boolean;
			}
): Exports;

mount

Mounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component. Transitions will play during the initial render unless the intro option is set to false.

function mount<
	Props extends Record<string, any>,
	Exports extends Record<string, any>
>(
	component:
		| ComponentType<SvelteComponent<Props>>
		| Component<Props, Exports, any>,
	options: MountOptions<Props>
): Exports;

onDestroy

Schedules a callback to run immediately before the component is unmounted.

Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.

function onDestroy(fn: () => any): void;

onMount

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

If a function is returned synchronously from onMount, it will be called when the component is unmounted.

onMount does not run inside a server-side component.

function onMount<T>(
	fn: () =>
		| NotFunction<T>
		| Promise<NotFunction<T>>
		| (() => any)
): void;

setContext

Associates an arbitrary context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.

Like lifecycle functions, this must be called during component initialisation.

function setContext<T>(key: any, context: T): T;

tick

Returns a promise that resolves once any pending state changes have been applied.

function tick(): Promise<void>;

unmount

Unmounts a component that was previously mounted using mount or hydrate.

function unmount(component: Record<string, any>): void;

untrack

Use untrack to prevent something from being treated as an $effect / $derived dependency.

https://svelte-5-preview.vercel.app/docs/functions#untrack

function untrack<T>(fn: () => T): T;

Component

Can be used to create strongly typed Svelte components.

Example:

You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you want to provide typings. Therefore you create a index.d.ts:

import type { interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>

Can be used to create strongly typed Svelte components.

Example:

You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you want to provide typings. Therefore you create a index.d.ts:

import type { Component } from 'svelte';
export declare const MyComponent: Component&#x3C;{ foo: string }> {}

Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:

&#x3C;script lang="ts">
	import { MyComponent } from "component-library";
&#x3C;/script>
&#x3C;MyComponent foo={'bar'} />
Component
} from 'svelte';
export declare const
const MyComponent: Component<{
    foo: string;
}, {}, string>
MyComponent
: interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>

Can be used to create strongly typed Svelte components.

Example:

You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you want to provide typings. Therefore you create a index.d.ts:

import type { Component } from 'svelte';
export declare const MyComponent: Component&#x3C;{ foo: string }> {}

Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:

&#x3C;script lang="ts">
	import { MyComponent } from "component-library";
&#x3C;/script>
&#x3C;MyComponent foo={'bar'} />
Component
<{ foo: stringfoo: string }> {}

Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:

<script lang="ts">
	import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
interface Component<
	Props extends Record<string, any> = {},
	Exports extends Record<string, any> = {},
	Bindings extends keyof Props | '' = string
> {}
(
	this: void,
	internals: ComponentInternals,
	props: Props
): {
	/**
	 * @deprecated This method only exists when using one of the legacy compatibility helpers, which
	 * is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes
	 * for more info.
	 */
	$on?(type: string, callback: (e: any) => void): () => void;
	/**
	 * @deprecated This method only exists when using one of the legacy compatibility helpers, which
	 * is a stop-gap solution. See https://svelte-5-preview.vercel.app/docs/breaking-changes#components-are-no-longer-classes
	 * for more info.
	 */
	$set?(props: Partial<Props>): void;
} & Exports;
  • internal An internal object used by Svelte. Do not use or modify.
  • props The props passed to the component.
element?: typeof HTMLElement;

The custom element version of the component. Only present if compiled with the customElement compiler option

ComponentConstructorOptions

In Svelte 4, components are classes. In Svelte 5, they are functions. Use mount instead to instantiate components. See breaking changes for more info.

interface ComponentConstructorOptions<
	Props extends Record<string, any> = Record<string, any>
> {}
target: Element | Document | ShadowRoot;
anchor?: Element;
props?: Props;
context?: Map<any, any>;
hydrate?: boolean;
intro?: boolean;
recover?: boolean;
sync?: boolean;
$$inline?: boolean;

ComponentEvents

The new Component type does not have a dedicated Events type. Use ComponentProps instead.

type ComponentEvents<Comp extends SvelteComponent> =
	Comp extends SvelteComponent<any, infer Events>
		? Events
		: never;

ComponentInternals

Internal implementation details that vary between environments

type ComponentInternals = Branded<{}, 'ComponentInternals'>;

ComponentProps

Convenience type to get the props the given component expects.

Example: Ensure a variable contains the props expected by MyComponent:

import type { type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : never

Convenience type to get the props the given component expects.

Example: Ensure a variable contains the props expected by MyComponent:

import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps&#x3C;MyComponent> = { foo: 'bar' };

Example: A generic function that accepts some component and infers the type of its props:

import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

function withProps&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
} from 'svelte';
import
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: ComponentType
MyComponent
from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent. const const props: Record<string, any>props: type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : never

Convenience type to get the props the given component expects.

Example: Ensure a variable contains the props expected by MyComponent:

import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps&#x3C;MyComponent> = { foo: 'bar' };

Example: A generic function that accepts some component and infers the type of its props:

import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

function withProps&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
<typeof const MyComponent: ComponentTypeMyComponent> = { foo: stringfoo: 'bar' };

In Svelte 4, you would do ComponentProps<MyComponent> because MyComponent was a class.

Example: A generic function that accepts some component and infers the type of its props:

import type { interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>

Can be used to create strongly typed Svelte components.

Example:

You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you want to provide typings. Therefore you create a index.d.ts:

import type { Component } from 'svelte';
export declare const MyComponent: Component&#x3C;{ foo: string }> {}

Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:

&#x3C;script lang="ts">
	import { MyComponent } from "component-library";
&#x3C;/script>
&#x3C;MyComponent foo={'bar'} />
Component
, type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : never

Convenience type to get the props the given component expects.

Example: Ensure a variable contains the props expected by MyComponent:

import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps&#x3C;MyComponent> = { foo: 'bar' };

Example: A generic function that accepts some component and infers the type of its props:

import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

function withProps&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
} from 'svelte';
import
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: ComponentType
MyComponent
from './MyComponent.svelte';
function function withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidwithProps<function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent extends interface Component<Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | "" = string>

Can be used to create strongly typed Svelte components.

Example:

You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you want to provide typings. Therefore you create a index.d.ts:

import type { Component } from 'svelte';
export declare const MyComponent: Component&#x3C;{ foo: string }> {}

Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:

&#x3C;script lang="ts">
	import { MyComponent } from "component-library";
&#x3C;/script>
&#x3C;MyComponent foo={'bar'} />
Component
<any>>(
component: TComponent extends Component<any>component: function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent, props: ComponentProps<TComponent>props: type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : never

Convenience type to get the props the given component expects.

Example: Ensure a variable contains the props expected by MyComponent:

import type { ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

// Errors if these aren't the correct props expected by MyComponent.
const props: ComponentProps&#x3C;MyComponent> = { foo: 'bar' };

Example: A generic function that accepts some component and infers the type of its props:

import type { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';

function withProps&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
<function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent>
) {}; // Errors if the second argument is not the correct props expected by the component in the first argument. function withProps<ComponentType>(component: ComponentType, props: Record<string, any>): voidwithProps(const MyComponent: ComponentTypeMyComponent, { foo: stringfoo: 'bar' });
type ComponentProps<
	Comp extends SvelteComponent | Component<any, any>
> =
	Comp extends SvelteComponent<infer Props>
		? Props
		: Comp extends Component<infer Props, any>
			? Props
			: never;

ComponentType

This type is obsolete when working with the new Component type.

type ComponentType<
	Comp extends SvelteComponent = SvelteComponent
> = (new (
	options: ComponentConstructorOptions<
		Comp extends SvelteComponent<infer Props>
			? Props
			: Record<string, any>
	>
) => Comp) & {
	/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */
	element?: typeof HTMLElement;
};

EventDispatcher

interface EventDispatcher<
	EventMap extends Record<string, any>
> {}
<Type extends keyof EventMap>(
	...args: null extends EventMap[Type]
		? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
		: undefined extends EventMap[Type]
			? [type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions]
			: [type: Type, parameter: EventMap[Type], options?: DispatchOptions]
): boolean;

MountOptions

Defines the options accepted by the mount() function.

type MountOptions<
	Props extends Record<string, any> = Record<string, any>
> = {
	/**
	 * Target element where the component will be mounted.
	 */
	target: Document | Element | ShadowRoot;
	/**
	 * Optional node inside `target` and when specified, it is used to render the component immediately before it.
	 */
	anchor?: Node;
	/**
	 * Allows the specification of events.
	 */
	events?: Record<string, (e: any) => any>;
	/**
	 * Used to define context at the component level.
	 */
	context?: Map<any, any>;
	/**
	 * Used to control transition playback on initial render.  The default value is `true` to run transitions.
	 */
	intro?: boolean;
} & ({} extends Props
	? {
			/**
			 * Component properties.
			 */
			props?: Props;
		}
	: {
			/**
			 * Component properties.
			 */
			props: Props;
		});

Snippet

The type of a #snippet block. You can use it to (for example) express that your component expects a snippet of a certain type:

let { 
let banner: Snippet<[{
    text: string;
}]>
banner
}: {
banner: Snippet<[{
    text: string;
}]>
banner
: type Snippet = /*unresolved*/ anySnippet<[{ text: stringtext: string }]> } = function $props(): any

Declares the props that a component accepts. Example:

let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();

https://svelte-5-preview.vercel.app/docs/runes#$props

$props
();

You can only call a snippet through the {@render ...} tag.

https://svelte-5-preview.vercel.app/docs/snippets

interface Snippet<Parameters extends unknown[] = []> {}
(
	this: void,
	// this conditional allows tuples but not arrays. Arrays would indicate a
	// rest parameter type, which is not supported. If rest parameters are added
	// in the future, the condition can be removed.
	...args: number extends Parameters['length'] ? never : Parameters
): {
	'{@render ...} must be called with a Snippet': "import type { Snippet } from 'svelte'";
} & typeof SnippetReturn;

SvelteComponent

This was the base class for Svelte components in Svelte 4. Svelte 5+ components are completely different under the hood. For typing, use Component instead. To instantiate components, use mount instead`. See breaking changes documentation for more info.

class SvelteComponent<
	Props extends Record<string, any> = Record<string, any>,
	Events extends Record<string, any> = any,
	Slots extends Record<string, any> = any
> {}
static element?: typeof HTMLElement;

The custom element version of the component. Only present if compiled with the customElement compiler option

[prop: string]: any;
constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);
$destroy(): void;
$on<K extends Extract<keyof Events, string>>(
	type: K,
	callback: (e: Events[K]) => void
): () => void;
$set(props: Partial<Props>): void;

SvelteComponentTyped

Use Component instead. See breaking changes documentation for more information.

class SvelteComponentTyped<
	Props extends Record<string, any> = Record<string, any>,
	Events extends Record<string, any> = any,
	Slots extends Record<string, any> = any
> extends SvelteComponent<Props, Events, Slots> {}

Edit this page on GitHub