svelte
import {
class SvelteComponent<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>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.
SvelteComponent,
class SvelteComponentTyped<Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any>SvelteComponentTyped,
function afterUpdate(fn: () => void): voidSchedules 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): voidSchedules 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 createContext<T>(): [() => T, (context: T) => T]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.
createContext,
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<{
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
}>();
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<T = void>(fn?: (() => T) | undefined): TSynchronously flush any pending updates.
Returns void if no callback is provided, otherwise returns the result of calling the callback.
flushSync,
function fork(fn: () => void): ForkCreates 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.
fork,
function getAbortSignal(): AbortSignalReturns 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>
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>
getAbortSignal,
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): TRetrieves 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): TRetrieves 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.
getContext,
function hasContext(key: any): booleanChecks whether a given key has been set in the context of a parent component.
Must be called during component initialisation.
hasContext,
function hydratable<T>(key: string, fn: () => T): Thydratable,
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
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: 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 onDestroy(fn: () => any): voidSchedules 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)): voidonMount, 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.
onMount,
function setContext<T>(key: any, context: T): TAssociates 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.
setContext,
function settled(): Promise<void>Returns a promise that resolves once any state changes, and asynchronous work resulting from them,
have resolved and the DOM has been updated
settled,
function tick(): Promise<void>Returns a promise that resolves once any pending state changes have been applied.
tick,
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,
function untrack<T>(fn: () => T): Tuntrack
} from 'svelte';SvelteComponent
Ceci était la classe de base pour les composants Svelte en Svelte 4. Les composants Svelte 5+ sont
d'une nature complètement différente. Pour le typeage, utilisez plutôt Component. Pour instancier
des composants, utilisez plutôt mount.
Voir le guide de migration pour
plus d'infos.
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;La version "élément personnalisé" du composant. Seulement présente si le composant est compilé avec
l'option de compilateur customElement.
[prop: string]: any;constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);- déprécié Cette méthode n'existe que si vous utilisez
l'utilitaire de compatibilité
asClassComponent, qui est une solution bouche-trou. Voir le guide de migration pour plus d'infos.
$destroy(): void;- déprécié Cette méthode n'existe que si vous utilisez un des utilitaires de compatibilité legacy, qui sont une solution bouche-trou. Voir le guide de migration pour plus d'infos.
$on<K extends Extract<keyof Events, string>>(
type: K,
callback: (e: Events[K]) => void
): () => void;- déprécié Cette méthode n'existe que si vous utilisez un des utilitaires de compatibilité legacy, qui sont une solution bouche-trou. Voir le guide de migration pour plus d'infos.
$set(props: Partial<Props>): void;- déprécié Cette méthode n'existe que si vous utilisez un des utilitaires de compatibilité legacy, qui sont une solution bouche-trou. Voir le guide de migration pour plus d'infos.
SvelteComponentTyped
Utilisez plutôt
Component. Voir le guide de migration pour plus d'infos.
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> {}afterUpdate
Utilisez plutôt [
$effect}(/docs/svelte/$effect)
Programme l'exécution d'un callback immédiatement après la mise à jour du composant.
La première exécution du callback aura lieu après le onMount initial.
En mode runes, utilisez plutôt $effect.
function afterUpdate(fn: () => void): void;beforeUpdate
Utilisez plutôt
$effect.pre.
Programme l'exécution d'un callback immédiatement avant la mise à jour du composant.
La première exécution du callback aura lieu avant le onMount initial.
En mode runes, utilisez plutôt $effect.pre.
function beforeUpdate(fn: () => void): void;createContext
Disponible depuis la version 5.40.0
Renvoie une paire de fonctions [get, set] permettant de travailler avec un contexte de manière
typée.
get va jeter une erreur si aucun composant parent n'a précédemment appelé set.
function createContext<T>(): [() => T, (context: T) => T];createEventDispatcher
Utilisez plutôt des props de callback et/ou la rune
$host()— voir le guide de migration.
Crée un générateur d'évènement qui peut être utilisé pour générer des évènements de
composant. Les générateurs d'évènement sont des fonctions
qui prennent deux arguments : name et detail.
Les évènements de composant créés avec createEventDispatcher créent un
CustomEvent. Ces évènements ne
"bubblent"
pas. L'argument detail correspond à la propriété
CustomEvent.detail et peut
contenir tout type de données.
Le générateur d'évènement peut être typé pour réduire les noms d'évènement autorisés et typer
l'argument detail :
const const dispatch: anydispatch = createEventDispatcher<{
loaded: nullloaded: null; // ne prend pas d'argument detail
change: stringchange: string; // prend un argument detail obligatoire de type string
optional: number | nulloptional: number | null; // prend un argument detail optionnel de type number
}>();function createEventDispatcher<
EventMap extends Record<string, any> = any
>(): EventDispatcher<EventMap>;createRawSnippet
Crée un snippet programmatiquement.
function createRawSnippet<Params extends unknown[]>(
fn: (...params: Getters<Params>) => {
render: () => string;
setup?: (element: Element) => void | (() => void);
}
): Snippet<Params>;flushSync
Force le traitement de manière synchrone de tout changement d'état en attente. Ne renvoie rien si aucun callback n'est fourni, renvoie le résultat de l'appel du callback sinon.
function flushSync<T = void>(fn?: (() => T) | undefined): T;fork
Disponible depuis la version 5.42
Crée un "fork", au sein duquel les changements d'état sont évalués mais pas appliqués au DOM. Cela sert à charger des données spéculativement (par exemple) lorsque vous suspectez que l'utilisateur ou l'utilisatrice est sur le point de réaliser une action.
Les frameworks comme SvelteKit peuvent se servir de cette API pour précharger des données lorsque l'utilisateur ou l'utilisatrice touche ou survole un lien, donnant aux navigations à venir un effet "instantané".
Le paramètre fn est une fonctino synchrone qui modifie l'état. Les changements d'état seront
annulés après l'initialisation du fork, puis ré-appliqués si et lorsque le fork sera appliqué pour
de bon.
Lorsqu'il apparaît évident qu'un fork ne sera pas appliqué pour de bon (par ex. parce que l'utilisateur ou l'utilisatrice a navigué vers un autre endroit), le fork doit être supprimé pour éviter des fuites de mémoire.
function fork(fn: () => void): Fork;getAbortSignal
Renvoie un AbortSignal qui
s'annule lorsque le $derived ou $effect courant
est ré-exécuté ou détruit.
Doit être appelée lorsqu'un $derived ou $effect est en cours d'exécution.
<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>function getAbortSignal(): AbortSignal;getAllContexts
Récupère la map complète des contextes appartenant au composant parent le plus proche. Doit être exécuté pendant l'initialisation du composant. Utile, par exemple, si vous créez programmatiquement un composant et souhaitez lui passer les contexte existant.
function getAllContexts<
T extends Map<any, any> = Map<any, any>
>(): T;getContext
Récupère le contexte nommé key appartenant au composant parent le plus proche. Doit être exécuté
pendant l'initialisation du composant.
createContext est une alternative typée.
function getContext<T>(key: any): T;hasContext
Vérifie si une clé key a été définie dans le contexte d'un composant parent. Doit être exécuté
pendant l'initialisation du composant.
function hasContext(key: any): boolean;hydratable
function hydratable<T>(key: string, fn: () => T): T;hydrate
Hydrate un composant sur la cible donnée et renvoie les exports et potentiellement les props du
composant (si compilé avec accessors: true).
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;mount
Monte un composant sur la cible donnée et renvoie les exports et potentiellement les props du
composant (si compilé avec accessors: true). Les transitions seront jouées pendant le rendu
initial à moins que l'option intro soit définie à 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
Programme l'exécution d'un callback immédiatement avant le démontage du composant.
Parmi onMount, beforeUpdate, afterUpdate et onDestroy, onDestroy est la seule fonction qui
est exécutée pendant le rendu côté serveur du composant.
function onDestroy(fn: () => any): void;onMount
onMount, comme $effect, prévoit d'exécuter une fonction dès que le
composant a été monté dans le DOM. À la différence de $effect, la fonction fournie ne sera
exécutée qu'une seule fois.
onMount doit être exécutée pendant l'initialisation du composant (mais n'a pas besoin de vivre au
sein du composant ; elle peut être appelée depuis un module externe). Si une fonction est renvoyée
de manière synchrone depuis onMount, celle-ci sera exécutée lorsque le composant sera démonté.
Les callbacks fournis à onMount ne sont pas exécutés pendant le rendu côté
serveur.
function onMount<T>(
fn: () =>
| NotFunction<T>
| Promise<NotFunction<T>>
| (() => any)
): void;setContext
Associe un objet de context arbitraire avec le composant courant et la clé fournie key, et
renvoie cet objet. Le contexte est rendu disponible pour les enfants du composant (incluant les
contenus slottés) avec getContext.
Comme pour les fonctions de cycle de vie, cette fonction doit être exécutée lors de l'initialisation du composant.
createContext est une alternative typée.
function setContext<T>(key: any, context: T): T;settled
Disponible depuis la version 5.36
Renvoie une promesse qui se résout une fois que tout état a changé, ainsi que tout travail asynchrone résultant de ces changements d'état se sont résolus et que le DOM a été mis à jour.
function settled(): Promise<void>;tick
Renvoie une promesse qui sera résolue lorsque tous les changements d'état en attente auront été appliqués.
function tick(): Promise<void>;unmount
Démonte un composant précédemment monté avec mount ou hydrate.
Depuis la version 5.13.0, si options.outro vaut true, les transitions
seront jouées avant que le composant soit retiré du DOM.
Renvoie une Promise qui résout après que les transitions se soient terminées si options.outro
vaut true, ou immédiatement sinon (avant la version 5.13.0, renvoie 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.
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 });
unmount } from 'svelte';
import 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>
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(const App: LegacyComponentTypeApp, { 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.
document.Document.body: HTMLElementThe Document.body property represents the 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 });
unmount(const app: {
$on?(type: string, callback: (e: any) => void): () => void;
$set?(props: Partial<Record<string, any>>): void;
} & Record<string, any>
app, { outro?: boolean | undefinedoutro: true });function unmount(
component: Record<string, any>,
options?:
| {
outro?: boolean;
}
| undefined
): Promise<void>;untrack
Lorsqu'utilisé dans un $derived ou un $effect,
tout état lu dans la fonction fn ne sera pas traité comme dépendance.
function $effect(fn: () => void | (() => void)): void
namespace $effect
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.
Does not run during server-side rendering.
$effect(() => {
// ceci sera exécuté lorsque `data` change, mais pas lorsque `time` change
save(data, {
timestamp: anytimestamp: untrack(() => time)
});
});function untrack<T>(fn: () => T): T;Component
Peut être utilisé pour créer des composants Svelte fortement typés.
Exemple :
Vous avez une librairie de composants sur npm appelée component-library, à partir de laquelle vous
exportez un composant appelé MyComponent. Vous souhaitez fournir du typage pour les personnes
utilisant Svelte+TypeScript. Vous créez donc un fichier index.d.ts :
import type { Component } from 'svelte';
export declare const MyComponent: Component<{ foo: string }> {}Typer de cette manière permet aux IDEs comme VS Code ayant l'extension Svelte de fournir les fonctionnalités intellisense, et donc d'utiliser le composants comme ceci dans un fichier Svelte avec 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 Cette méthode n'existe que lorsque vous utilisez un des utilitaires de
* compatibilité, qui sont des solutions bouche-trous. Voir le [guide de migration](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes)
* pour plus d'infos.
*/
$on?(type: string, callback: (e: any) => void): () => void;
/**
* @deprecated Cette méthode n'existe que lorsque vous utilisez un des utilitaires de
* compatibilité, qui sont des solutions bouche-trous. Voir le [guide de migration](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes).
* pour plus d'infos.
*/
$set?(props: Partial<Props>): void;
} & Exports;internalUn objet interne utilisé par Svelte. Ne pas utiliser ou modifier.propsLes props passées au composant.
element?: typeof HTMLElement;La version "élément personnalisé" du composant. Seulement présente si le composant est compilé avec
l'option de compilateur customElement.
ComponentConstructorOptions
In Svelte 4, components are classes. In Svelte 5, they are functions.
Utilisez plutôt
mountpour instancier des composants. Voir guide de migration pour plus d'infos.
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;idPrefix?: string;$$inline?: boolean;transformError?: (error: unknown) => unknown;ComponentEvents
Le nouveau type
Componentn'a pas de type dédié pour les Events. Utilisez plutôtComponentProps.
type ComponentEvents<Comp extends SvelteComponent> =
Comp extends SvelteComponent<any, infer Events>
? Events
: never;ComponentInternals
Détails d'implémentation interne qui changent selon l'environnement.
type ComponentInternals = Branded<{}, 'ComponentInternals'>;ComponentProps
Type utilitaire pour obtenir les props qu'un certain composant attend.
Exemple : vous voulez vous assurer qu'une variable contient les props attendues par 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' };
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
MyComponent from './MyComponent.svelte';
// Affiche une erreur si on ne fournit pas les bonnes props à 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<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' };
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: LegacyComponentTypeMyComponent> = { foo: stringfoo: 'bar' };En Svelte 4, vous feriez
ComponentProps<MyComponent>carMyComponentétait une classe.
Exemple : une fonction générique qui accepte un composant et en déduit le type de ses 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'} />
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' };
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
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<{ 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: 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<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' };
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>): voidTComponent>
) {};
// Affiche une erreur si le deuxième argument ne correspond pas aux props attendues par le composant
// fourni en premier argument.
function withProps<LegacyComponentType>(component: LegacyComponentType, props: Record<string, any>): voidwithProps(const MyComponent: LegacyComponentTypeMyComponent, { 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
Ce type est obsolète lorsque vous utilisez le nouveau type
Component.
type ComponentType<
Comp extends SvelteComponent = SvelteComponent
> = (new (
options: ComponentConstructorOptions<
Comp extends SvelteComponent<infer Props>
? Props
: Record<string, any>
>
) => Comp) & {
/** La version "élément personnalisé" du composant. N'est présent que si le composant est compilé
* avec l'option de compilateur `customElement`.
*/
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;Fork
Disponible depuis la version 5.42
Représente des tâches se produisant hors de l'écran, telles que des préchargements de données en anticipation d'une navigation.
interface Fork {…}commit(): Promise<void>;Applique le fork pour de bon. La promesse sera résolue lorsque le changement d'état aura été appliqué
discard(): void;Supprime le fork
MountOptions
Définit les options acceptées par la fonction mount().
type MountOptions<
Props extends Record<string, any> = Record<string, any>
> = {
/**
* L'élément cible où le composant doit être monté.
*/
target: Document | Element | ShadowRoot;
/**
* Un noeud optionnel dans `target`. Lorsque fourni, il est utilisé pour rendre le composant juste
* immédiatement avant lui.
*/
anchor?: Node;
/**
* Permet la spécification des évènements.
* @deprecated Utilisez plutôt les props de callback.
*/
events?: Record<string, (e: any) => any>;
/**
* Peut être obtenu via `getContext()` au niveau du composant.
*/
context?: Map<any, any>;
/**
* Si oui ou non il faut jouer les transitions lors du rendu initial.
* @default true
*/
intro?: boolean;
/**
* Une fonction qui transforme les erreurs attrapées par les frontières d'erreur avant qu'elles ne
* soient passées au snippet `failed`.
* Vaut par défaut la fonction identité.
*/
transformError?: (
error: unknown
) => unknown | Promise<unknown>;
} & ({} extends Props
? {
/**
* Component properties.
*/
props?: Props;
}
: {
/**
* Component properties.
*/
props: Props;
});Snippet
Le type d'un bloc $snippet. Vous pouvez l'utilisez pour (par exemple) exprimer le fait que votre
composant attend un snippet d'un certain type :
let { let banner: Snippet<[{
text: string;
}]>
banner }: { banner: Snippet<[{
text: string;
}]>
banner: type Snippet = /*unresolved*/ anySnippet<[{ text: stringtext: string }]> } = function $props(): any
namespace $props
Declares the props that a component accepts. Example:
let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();
$props();Vous pouvez uniquement appeler un snippet via la balise {@render ...}.
Voir la documentation des snippets pour plus d'info.
interface Snippet<Parameters extends unknown[] = []> {…}(
this: void,
// cette condition autorise les tuples mais pas les tableaux. Utiliser des tableaux nécessiterait
// un type de paramètre de reste, ce qui n'est pas supporté. Si les paramètre de reste sont
// ajoutés dans le futur, cette condition pourra être supprimée.
...args: number extends Parameters['length'] ? never : Parameters
): {
'{@render ...} doit être appelée avec un Snippet': "import type { Snippet } from 'svelte'";
} & typeof SnippetReturn;Modifier cette page sur Github llms.txt