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.
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:
constdispatch=createEventDispatcher<{loaded:null;// does not take a detail argumentchange:string;// takes a detail argument of type string, which is requiredoptional:number|null;// takes an optional detail argument of type number}>();
Use callback props and/or the $host() rune instead — see migration guide
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.
Retrieves the whole context map that belongs to the current component, including entries
inherited from its ancestors. Must be called during component initialisation. Useful, for
example, if you programmatically create a component and want to pass the existing context to it.
Retrieves the context set with the specified key in the current component or any of its
ancestors. If multiple components set the same key, the value from the closest one is returned.
A setContext call in the current component is only visible to getContext calls that run after it.
Must be called during component initialisation.
Checks whether a given key has been set in the context of the current component or any of
its ancestors. Must be called during component initialisation.
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.
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.
Associates an arbitrary context object with the current component and the specified key
and returns that object. The context is then available to the component itself and all of its
descendants (including slotted content) with getContext.
Like lifecycle functions, this must be called during component initialisation.
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.
deprecated This constructor only exists when using the asClassComponent compatibility helper, which
is a stop-gap solution. Migrate towards using mount instead. See
migration guide for more info.
$destroy():void;
deprecated This method only exists when using one of the legacy compatibility helpers, which
is a stop-gap solution. See migration guide
for more info.
deprecated This method only exists when using one of the legacy compatibility helpers, which
is a stop-gap solution. See migration guide
for more info.
$set(props:Partial<Props>):void;
deprecated This method only exists when using one of the legacy compatibility helpers, which
is a stop-gap solution. See migration guide
for more info.
SvelteComponentTyped
Use Component instead. See migration guide for more information.
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:
constdispatchconstdispatch:any=createEventDispatcherany<{loaded(property)loaded:null:null;// does not take a detail argumentchange(property)change:string:string;// takes a detail argument of type string, which is requiredoptional(property)optional:number|null:number|null;// takes an optional detail argument of type number}>();
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.
Retrieves the whole context map that belongs to the current component, including entries
inherited from its ancestors. Must be called during component initialisation. Useful, for
example, if you programmatically create a component and want to pass the existing context to it.
Retrieves the context set with the specified key in the current component or any of its
ancestors. If multiple components set the same key, the value from the closest one is returned.
A setContext call in the current component is only visible to getContext calls that run after it.
Must be called during component initialisation.
Checks whether a given key has been set in the context of the current component or any of
its ancestors. Must be called during component initialisation.
functionhasContext(key:any):boolean;
hydratable
functionhydratable<T>(key:string,fn:()=>T):T;
hydrate
Hydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component
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.
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.
functiononDestroy(fn:()=>any):void;
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.
Associates an arbitrary context object with the current component and the specified key
and returns that object. The context is then available to the component itself and all of its
descendants (including slotted content) with getContext.
Like lifecycle functions, this must be called during component initialisation.
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.
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.
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e. $state or $derived values.
The timing of the execution is after the DOM has been updated.
Example:
$effect(()=>console.log('The count is now '+count));
If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
(()=>{ // this will run when `data` changes, but not when `time` changes
saveany(dataany,{timestamp(property)timestamp:any:untrackany(()=>timeany)});});
functionuntrack<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:
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:
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:
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:
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:
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:
(this:void,internals:ComponentInternals,props:Props):{/***@deprecatedThis 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;/***@deprecatedThis 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;
internal An internal object used by Svelte. Do not use or modify.
props The props passed to the component.
element?:typeofHTMLElement;
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 migration guide
for more info.
Convenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
importtype{ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.constprops:ComponentProps<typeofMyComponent>={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:
importtype{Component,ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';functionwithProps<TComponentextendsComponent<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'});
reference}from'svelte';importMyComponent(alias)typeMyComponent=SvelteComponent<Record<string,any>,any,any>(alias)constMyComponent:LegacyComponentTypeimportMyComponentfrom'./MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.
constpropsconstprops:Record<string,any>:ComponentProps(alias)typeComponentProps<CompextendsSvelteComponent|Component<any,any>>=CompextendsSvelteComponent<inferPropsextendsRecord<string,any>,any,any>?Props:CompextendsComponent<inferPropsextendsRecord<string,any>,any,string>?Props:neverimportComponentProps
Convenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
importtype{ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.constprops:ComponentProps<typeofMyComponent>={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:
importtype{Component,ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';functionwithProps<TComponentextendsComponent<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'});
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:
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:
Convenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
importtype{ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.constprops:ComponentProps<typeofMyComponent>={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:
importtype{Component,ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';functionwithProps<TComponentextendsComponent<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'});
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:
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:
Convenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by MyComponent:
importtype{ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.constprops:ComponentProps<typeofMyComponent>={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:
importtype{Component,ComponentProps}from'svelte';importMyComponentfrom'./MyComponent.svelte';functionwithProps<TComponentextendsComponent<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'});
reference<TComponent(typeparameter)TComponentinwithProps<TComponentextendsComponent<any>>(component:TComponent,props:ComponentProps<TComponent>):void>){};// Errors if the second argument is not the correct props expected by the component in the first argument.
withPropsfunctionwithProps<LegacyComponentType>(component:LegacyComponentType,props:Record<string,any>):void(MyComponent(alias)constMyComponent:LegacyComponentTypeimportMyComponent,{foo(property)foo:string:'bar'});
This type is obsolete when working with the new Component type.
typeComponentType<CompextendsSvelteComponent=SvelteComponent>=(new(options:ComponentConstructorOptions<CompextendsSvelteComponent<inferProps>?Props:Record<string,any>>)=>Comp)&{/** The custom element version of the component. Only present if compiled with the `customElement` compiler option */element?:typeofHTMLElement;};
Represents work that is happening off-screen, such as data being preloaded
in anticipation of the user navigating
interfaceFork{/*…*/}
commit():Promise<void>;
Commit the fork. The promise will resolve once the state change has been applied
discard():void;
Discard the fork
MountOptions
Defines the options accepted by the mount() function.
typeMountOptions<PropsextendsRecord<string,any>=Record<string,any>>={/*** Target 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;/*** Allows the specification of events.*@deprecatedUse callback props instead.*/events?:Record<string,(e:any)=>any>;/*** Can be accessed via `getContext()` at the component level.*/context?:Map<any,any>;/*** Whether or not to play transitions on initial render.*@defaulttrue*/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>;}&({}extendsProps?{/*** 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:
(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:numberextendsParameters['length']?never:Parameters):{'{@render ...} must be called with a Snippet':"import type { Snippet } from 'svelte'";}&typeofSnippetReturn;