Svelte • Reference
svelte
On this page
- ComponentConstructorOptions
- SvelteComponent
- DO NOT USE!
- DO NOT USE!
- DO NOT USE!
- DO NOT USE!
- ComponentInternals
- Component
- Example:
- SvelteComponentTyped
- ComponentEvents
- ComponentProps
- ComponentType
- Snippet
- EventDispatcher
- MountOptions
- Fork
- getAbortSignal
- onMount
- onDestroy
- createEventDispatcher
- beforeUpdate
- afterUpdate
- hydratable
- createRawSnippet
- flushSync
- fork
- createContext
- getContext
- setContext
- hasContext
- getAllContexts
- mount
- hydrate
- unmount
- tick
- settled
- untrack
import {
afterUpdate,
beforeUpdate,
Component,
ComponentConstructorOptions,
ComponentEvents,
ComponentInternals,
ComponentProps,
ComponentType,
createContext,
createEventDispatcher,
createRawSnippet,
EventDispatcher,
flushSync,
fork,
Fork,
getAbortSignal,
getAllContexts,
getContext,
hasContext,
hydratable,
hydrate,
mount,
MountOptions,
onDestroy,
onMount,
setContext,
settled,
Snippet,
SvelteComponent,
SvelteComponentTyped,
tick,
unmount,
untrack
} from 'svelte';ComponentConstructorOptions
In Svelte 4, components are classes. In Svelte 5, they are functions. Use
mountinstead to instantiate components. See migration guide for more info.
export interface interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>>interface ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>>ComponentConstructorOptions<
function (type parameter) Props in ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>>function (type parameter) Props in ComponentConstructorOptions<Props extends Record<string, any> = Record<string, any>>Props extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>
> {/*…*/}target: Element | Document | ShadowRoot;anchor?: Element;props?: Props;context?: Map<any, any>;hydrate?: boolean;intro?: boolean;recover?: boolean;sync?: boolean;idPrefix?: string;$$inline?: boolean;transformError?: (error: unknown) => unknown;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 migration guide for more info.
export class class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>SvelteComponent<
function (type parameter) Props in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>function (type parameter) Props in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>Props extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>,
function (type parameter) Events in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>function (type parameter) Events in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>Events extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> = any,
function (type parameter) Slots in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>function (type parameter) Slots in SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>Slots extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
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;ComponentInternals
Internal implementation details that vary between environments
export type ComponentInternals = Branded<{}, 'ComponentInternals'>;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 { Component } from 'svelte';
export declare const MyComponent: Component<{ 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:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />export interface Component<
Props extends Record<string, any> = {/*…*/}(
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 [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#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 [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* for more info.
*/
$set?(props: Partial<Props>): void;
} & Exports;element?: typeof HTMLElement;The custom element version of the component. Only present if compiled with the customElement compiler option
z_$$bindings?: Bindings;Does not exist at runtime, for typing capabilities only. DO NOT USE
SvelteComponentTyped
Use
Componentinstead. See migration guide for more information.
export 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> {}ComponentEvents
The new
Componenttype does not have a dedicated Events type. UseComponentPropsinstead.
export type ComponentEvents<Comp extends SvelteComponent> =
Comp extends SvelteComponent<any, infer Events> ? Events : never;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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<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: LegacyComponentType
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: LegacyComponentType
MyComponent from './MyComponent.svelte';
// Errors if these aren't the correct props expected by MyComponent.
const const props: Record<string, any>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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<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: LegacyComponentTypeconst MyComponent: LegacyComponentTypeMyComponent> = { foo: stringfoo: stringfoo: 'bar' };In Svelte 4, you would do
ComponentProps<MyComponent>becauseMyComponentwas 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<{ 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:
<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>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<{ 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:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<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: LegacyComponentType
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: LegacyComponentType
MyComponent from './MyComponent.svelte';
function function withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidfunction 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>): voidfunction (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<{ 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:
<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>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<{ 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:
<script lang="ts">
import { MyComponent } from "component-library";
</script>
<MyComponent foo={'bar'} />
Component<any>>(
component: TComponent extends Component<any>component: TComponent extends Component<any>component: function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidfunction (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent,
props: ComponentProps<TComponent>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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<TComponent>
) {};
// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
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<string, any>, any, string> ? Props : neverConvenience 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<typeof MyComponent> = { foo: 'bar' };
[!NOTE] 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 { Component, ComponentProps } from 'svelte';
import MyComponent from './MyComponent.svelte';
function withProps<TComponent extends Component<any>>(
component: TComponent,
props: ComponentProps<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>): voidfunction (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<LegacyComponentType>(component: LegacyComponentType, props: Record<string, any>): voidfunction withProps<LegacyComponentType>(component: LegacyComponentType, props: Record<string, any>): voidwithProps(const MyComponent: LegacyComponentTypeconst MyComponent: LegacyComponentTypeMyComponent, { foo: stringfoo: stringfoo: 'bar' });export 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
Componenttype.
export 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;
};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 { banner }: { banner: Snippet<[{ text: string }]> } = $props();You can only call a snippet through the {@render ...} tag.
See the snippet documentation for more info.
export interface interface Snippet<Parameters extends unknown[] = []>interface Snippet<Parameters extends unknown[] = []>Snippet<function (type parameter) Parameters in Snippet<Parameters extends unknown[] = []>function (type parameter) Parameters in Snippet<Parameters extends unknown[] = []>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;EventDispatcher
export interface interface EventDispatcher<EventMap extends Record<string, any>>interface EventDispatcher<EventMap extends Record<string, any>>EventDispatcher<function (type parameter) EventMap in EventDispatcher<EventMap extends Record<string, any>>function (type parameter) EventMap in EventDispatcher<EventMap extends Record<string, any>>EventMap extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
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.
export type type MountOptions<Props extends Record<string, any> = Record<string, any>> = {
target: Document | Element | ShadowRoot;
anchor?: Node;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
transformError?: (error: unknown) => unknown | Promise<unknown>;
} & ({} extends Props ? {
props?: Props;
} : {
props: Props;
})
type MountOptions<Props extends Record<string, any> = Record<string, any>> = {
target: Document | Element | ShadowRoot;
anchor?: Node;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
transformError?: (error: unknown) => unknown | Promise<unknown>;
} & ({} extends Props ? {
props?: Props;
} : {
props: Props;
})
MountOptions<function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>Props extends type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any> = type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, any>> = {
/**
* Target element where the component will be mounted.
*/
target: Document | Element | ShadowRootTarget element where the component will be mounted.
target: Document | Element | ShadowRootTarget element where the component will be mounted.
target: Document | Element | ShadowRoot;
/**
* Optional node inside `target`. When specified, it is used to render the component immediately before it.
*/
anchor?: Node | undefinedOptional node inside target. When specified, it is used to render the component immediately before it.
anchor?: Node | undefinedOptional node inside target. When specified, it is used to render the component immediately before it.
anchor?: Node;
/**
* Allows the specification of events.
* @deprecated Use callback props instead.
*/
events?: Record<string, (e: any) => any> | undefinedAllows the specification of events.
events?: Record<string, (e: any) => any> | undefinedAllows the specification of events.
events?: type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
type Record<K extends keyof any, T> = { [P in K]: T; }Construct a type with a set of properties K of type T
Record<string, (e: anye: anye: any) => any>;
/**
* Can be accessed via `getContext()` at the component level.
*/
context?: Map<any, any> | undefinedCan be accessed via getContext() at the component level.
context?: Map<any, any> | undefinedCan be accessed via getContext() at the component level.
context?: interface Map<K, V>interface Map<K, V>Map<any, any>;
/**
* Whether or not to play transitions on initial render.
* @default true
*/
intro?: boolean | undefinedWhether or not to play transitions on initial render.
intro?: boolean | undefinedWhether or not to play transitions on initial render.
intro?: boolean;
/**
* A function that transforms errors caught by error boundaries before they are passed to the `failed` snippet.
* Defaults to the identity function.
*/
transformError?: ((error: unknown) => unknown | Promise<unknown>) | undefinedA function that transforms errors caught by error boundaries before they are passed to the failed snippet.
Defaults to the identity function.
transformError?: ((error: unknown) => unknown | Promise<unknown>) | undefinedA function that transforms errors caught by error boundaries before they are passed to the failed snippet.
Defaults to the identity function.
transformError?: (error: unknownerror: unknownerror: unknown) => unknown | interface Promise<T>Represents the completion of an asynchronous operation
interface Promise<T>Represents the completion of an asynchronous operation
Promise<unknown>;
} & ({} extends function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>Props
? {
/**
* Component properties.
*/
props?: Props | undefinedComponent properties.
props?: Props | undefinedComponent properties.
props?: function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>Props;
}
: {
/**
* Component properties.
*/
props: Props extends Record<string, any> = Record<string, any>Component properties.
props: Props extends Record<string, any> = Record<string, any>Component properties.
props: function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>function (type parameter) Props in type MountOptions<Props extends Record<string, any> = Record<string, any>>Props;
});Fork
Available since 5.42
Represents work that is happening off-screen, such as data being preloaded in anticipation of the user navigating
export interface Fork {/*…*/}commit(): Promise<void>;Commit the fork. The promise will resolve once the state change has been applied
discard(): void;Discard the fork
getAbortSignal
Returns an AbortSignal that aborts when the current derived or effect re-runs or is destroyed.
Must be called while a derived or effect is running.
<script lang="ts">
import { getAbortSignal } from 'svelte';
let { id } = $props();
async function getData(id) {
const response = await fetch(`/items/${id}`, {
signal: getAbortSignal()
});
return await response.json();
}
const data = $derived(await getData(id));
</script><script>
import { getAbortSignal } from 'svelte';
let { id } = $props();
async function getData(id) {
const response = await fetch(`/items/${id}`, {
signal: getAbortSignal()
});
return await response.json();
}
const data = $derived(await getData(id));
</script>export function getAbortSignal(): AbortSignal;onMount
onMount, like $effect, schedules a function to run as soon as the component has been mounted to the DOM.
Unlike $effect, the provided function only runs once.
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 functions do not run during server-side rendering.
export function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;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.
export function onDestroy(fn: () => any): void;createEventDispatcher
Use callback props and/or the
$host()rune instead — see migration guide
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<{
loaded: null; // 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
}>();export function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>;beforeUpdate
Use
$effect.preinstead
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.
export function beforeUpdate(fn: () => void): void;afterUpdate
Use
$effectinstead
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.
export function afterUpdate(fn: () => void): void;hydratable
export function hydratable<T>(key: string, fn: () => T): T;createRawSnippet
Create a snippet programmatically
export function createRawSnippet<Params extends unknown[]>(fn: (...params: Getters<Params>) => {
render: () => string;
setup?: (element: Element) => void | (() => void);
}): Snippet<Params>;flushSync
Synchronously flush any pending updates. Returns void if no callback is provided, otherwise returns the result of calling the callback.
export function flushSync<T = void>(fn?: (() => T) | undefined): T;fork
Available since 5.42
Creates a 'fork', in which state changes are evaluated but not applied to the DOM. This is useful for speculatively loading data (for example) when you suspect that the user is about to take some action.
Frameworks like SvelteKit can use this to preload data when the user touches or hovers over a link, making any subsequent navigation feel instantaneous.
The fn parameter is a synchronous function that modifies some state. The
state changes will be reverted after the fork is initialised, then reapplied
if and when the fork is eventually committed.
When it becomes clear that a fork will not be committed (e.g. because the user navigated elsewhere), it must be discarded to avoid leaking memory.
export function fork(fn: () => void): Fork;createContext
Available since 5.40.0
Returns a [get, set] pair of functions for working with context in a type-safe way.
get will throw an error if no parent component called set.
export function createContext<T>(): [() => T, (context: T) => T];getContext
Retrieves the context that belongs to the closest parent component with the specified key.
Must be called during component initialisation.
createContext is a type-safe alternative.
export function getContext<T>(key: any): T;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.
createContext is a type-safe alternative.
export function setContext<T>(key: any, context: T): T;hasContext
Checks whether a given key has been set in the context of a parent component.
Must be called during component initialisation.
export function hasContext(key: any): boolean;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.
export function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;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.
export function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>): Exports;hydrate
Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component
export 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;
transformError?: (error: unknown) => unknown;
} : {
target: Document | Element | ShadowRoot;
props: Props;
events?: Record<string, (e: any) => any>;
context?: Map<any, any>;
intro?: boolean;
recover?: boolean;
transformError?: (error: unknown) => unknown;
}): Exports;unmount
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { function mount<Props extends Record<string, any>, Exports extends Record<string, any>>(component: ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>): ExportsMounts 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>): ExportsMounts 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 unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
unmount } from 'svelte';
import type App = SvelteComponent<Record<string, any>, any, any>
const App: LegacyComponentType
type App = SvelteComponent<Record<string, any>, any, any>
const App: LegacyComponentType
App from './App.svelte';
const const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
app = mount<Record<string, any>, {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>>(component: ComponentType<SvelteComponent<Record<string, any>, any, any>> | Component<Record<string, any>, {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>, any>, options: MountOptions<...>): {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<...>
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<Record<string, any>, {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>>(component: ComponentType<SvelteComponent<Record<string, any>, any, any>> | Component<Record<string, any>, {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>, any>, options: MountOptions<...>): {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<...>
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(const App: LegacyComponentTypeconst App: LegacyComponentTypeApp, { target: Document | Element | ShadowRootTarget element where the component will be mounted.
target: Document | Element | ShadowRootTarget element where the component will be mounted.
target: var document: Documentwindow.document returns a reference to the document contained in the window.
var document: Documentwindow.document returns a reference to the document contained in the window.
document.Document.body: HTMLElementThe Document.body property represents the or node of the current document, or null if no such element exists.
Document.body: HTMLElementThe Document.body property represents the or node of the current document, or null if no such element exists.
body });
// later...
function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>
Unmounts a component that was previously mounted using mount or hydrate.
Since 5.13.0, if options.outro is true, transitions will play before the component is removed from the DOM.
Returns a Promise that resolves after transitions have completed if options.outro is true, or immediately otherwise (prior to 5.13.0, returns void).
import { mount, unmount } from 'svelte';
import App from './App.svelte';
const app = mount(App, { target: document.body });
// later...
unmount(app, { outro: true });
unmount(const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
app, { outro?: boolean | undefinedoutro?: boolean | undefinedoutro: true });export function unmount(component: Record<string, any>, options?: {
outro?: boolean;
} | undefined): Promise<void>;tick
Returns a promise that resolves once any pending state changes have been applied.
export function tick(): Promise<void>;settled
Available since 5.36
Returns a promise that resolves once any state changes, and asynchronous work resulting from them, have resolved and the DOM has been updated
export function settled(): Promise<void>;untrack
When used inside a $derived or $effect,
any state read inside fn will not be treated as a dependency.
$effect(() => {
// this will run when `data` changes, but not when `time` changes
save(data, {
timestamp: untrack(() => time)
});
});export function untrack<T>(fn: () => T): T;