Skip to main content

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>
@deprecatedUse Component instead. See migration guide for more information.
SvelteComponentTyped
,
function afterUpdate(fn: () => void): void

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

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

In runes mode use $effect instead.

@deprecatedUse $effect instead
afterUpdate
,
function beforeUpdate(fn: () => void): void

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

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

In runes mode use $effect.pre instead.

@deprecatedUse $effect.pre instead
beforeUpdate
,
function createEventDispatcher<EventMap extends Record<string, any> = any>(): EventDispatcher<EventMap>

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

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

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

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

Create a snippet programmatically

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

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

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

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

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

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

getContext
,
function hasContext(key: any): boolean

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

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

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

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

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

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

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

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

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

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

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

onMount does not run inside server-side components.

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

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

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

setContext
,
function tick(): Promise<void>

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

tick
,
function unmount(component: Record<string, any>, 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): T

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)
  });
});
untrack
} from 'svelte';

SvelteComponent

这是 Svelte 4 中 Svelte 组件的基本类。Svelte 5+ 组件在底层实现上完全不同。对于类型定义,请改用 Component。要实例化组件,请改用 mount。更多信息请参阅 迁移指南

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;

组件的自定义元素版本。仅当使用 customElement 编译选项编译时才存在。

[prop: string]: any;
constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);
  • 已废弃 该构造函数仅在使用 asClassComponent 兼容辅助工具时存在,这是一个临时解决方案。请迁移至使用 mount。更多信息请参阅迁移指南
$destroy(): void;
  • 已废弃 该方法仅在使用某个遗留兼容辅助工具时存在,这是一个临时解决方案。更多信息请参阅迁移指南
$on<K extends Extract<keyof Events, string>>(
	type: K,
	callback: (e: Events[K]) => void
): () => void;
  • 已废弃 该方法仅在使用某个遗留兼容辅助工具时存在,这是一个临时解决方案。更多信息请参阅迁移指南
$set(props: Partial<Props>): void;
  • 已废弃 该方法仅在使用某个遗留兼容辅助工具时存在,这是一个临时解决方案。更多信息请参阅迁移指南

SvelteComponentTyped

请使用 Component 替代。有关更多信息,请参见 迁移指南

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

请使用 $effect 替代。

调度一个回调函数在组件更新后立即运行。

回调第一次运行将在初始 onMount 之后。

在符文模式下使用 $effect 替代。

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

beforeUpdate

请使用 $effect.pre 替代。

调度一个回调函数在组件在状态变化后更新之前立即运行。

回调第一次运行将在初始 onMount 之前。

在符文模式下使用 $effect.pre 替代。

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

createEventDispatcher

请使用回调属性和/或 $host() 符文替代 - 请参见 迁移指南

创建一个事件分发器,用于分发 组件事件。 事件分发器是可以接受两个参数的函数:namedetail

使用 createEventDispatcher 创建的组件事件会创建一个 CustomEvent。 这些事件不会 冒泡detail 参数对应于 CustomEvent.detail 属性,并且可以包含任何类型的数据。

事件分发器可以被类型化以收窄允许的事件名称和 detail 参数的类型:

const const dispatch: anydispatch = createEventDispatcher<{
	loaded: neverloaded: never; // 不接受 detail 参数
	change: stringchange: string; // 接受类型为 string 的 detail 参数,该参数是必需的
	optional: number | nulloptional: number | null; // 接受可选的类型为 number 的 detail 参数
}>();
function createEventDispatcher<
	EventMap extends Record<string, any> = any
>(): EventDispatcher<EventMap>;

createRawSnippet

以编程方式创建一个代码片段。

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

flushSync

同步刷新任何待处理的状态更改和由此产生的结果。

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

getAllContexts

获取最近父组件的完整上下文映射。必须在组件初始化期间调用。例如,当你以编程方式创建组件并想要将现有上下文传递给它时,这个方法很有用。

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

getContext

获取属于具有指定 key 的最近父组件的上下文。必须在组件初始化期间调用。

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

hasContext

检查给定的 key 是否已在父组件的上下文中设置。 必须在组件初始化期间调用。

function hasContext(key: any): boolean;

hydrate

在给定目标上水合组件,并返回该组件的导出和可能的 props(如果编译时使用了 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;
			}
		: {
				target: Document | Element | ShadowRoot;
				props: Props;
				events?: Record<string, (e: any) => any>;
				context?: Map<any, any>;
				intro?: boolean;
				recover?: boolean;
			}
): Exports;

mount

将组件挂载到指定目标并返回该组件的导出和可能的 props(如果编译时使用了 accessors: true)。 在初始渲染时,过渡效果将会播放,除非 intro 选项设置为 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

调度一个回调在组件卸载之前立即运行。

onMountbeforeUpdateafterUpdateonDestroy 中,这个是唯一一个在服务端组件内运行的。

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

onMount

onMount 函数调度一个回调函数在组件被挂载到 DOM 后立即运行。 它必须在组件初始化时调用(但不必“在”组件内部;可以从外部模块调用)。

如果从 onMount 返回一个 同步 的函数,那么它将在组件卸载时被调用。

onMount 不会在 服务端组件 内部运行。

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

setContext

将任意 context 对象与当前组件和指定的 key 关联并返回该对象。之后,子组件(包括插槽内容)可以使用 getContext 来访问该上下文。

与生命周期函数一样,这必须在组件初始化期间调用。

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

tick

返回一个 Promise,在所有待处理的状态更改应用后,该 Promise 将 resolve。

function tick(): Promise<void>;

unmount

卸载之前使用 mounthydrate 挂载的组件。

从 5.13.0 版本开始,如果 options.outrotrue过渡效果将在组件从 DOM 中移除之前播放。

返回一个 Promise,如果 options.outro 为 true,则在过渡完成后 resolve,否则立即 resolve(在 5.13.0 之前,返回 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>): Exports

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

mount
,
function 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<...>>(component: ComponentType<...> | Component<...>, options: MountOptions<...>): {
    ...;
} & 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 | ShadowRoot

Target element where the component will be mounted.

target
: var document: Documentdocument.Document.body: HTMLElement

Specifies the beginning and end of the document body.

MDN Reference

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

$derived$effect 内部使用时,在 fn 内部读取的任何状态将不会被视为依赖项。

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.

https://svelte.dev/docs/svelte/$effect

@paramfn The function to execute
$effect
(() => {
// 当 `data` 更改时将运行,但当 `time` 更改时不会 save(data, { timestamp: anytimestamp: untrack(() => time) }); });
function untrack<T>(fn: () => T): T;

Component

可以用来创建强类型的 Svelte 组件。

示例:

你有一个名为 component-library 的 npm 组件库,从中导出一个名为 MyComponent 的组件。对于 Svelte + TypeScript 用户,你希望提供类型定义。因此你创建了一个 index.d.ts

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

Can be used to create strongly typed Svelte components.

Example:

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

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

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

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

Can be used to create strongly typed Svelte components.

Example:

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

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

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

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

这样类型定义可以让像 VS Code 这样的 IDE 在 Svelte 扩展的帮忙下提供智能提示,并且可以在带有 TypeScript 的 Svelte 文件中这样使用组件:

<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 该方法仅在使用某个遗留兼容助手时存在,这是一个权宜之计解决方案。请参见 [迁移指南](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) 以获取更多信息。
	 */
	$on?(type: string, callback: (e: any) => void): () => void;
	/**
	 * @deprecated 该方法仅在使用某个遗留兼容助手时存在,这是一个权宜之计解决方案。请参见 [迁移指南](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) 以获取更多信息。
	 */
	$set?(props: Partial<Props>): void;
} & Exports;
  • internal Svelte 使用的内部对象。请勿使用或修改。
  • props 传递给组件的 props。
element?: typeof HTMLElement;

组件的自定义元素版本。仅在使用 customElement 编译器选项编译时才存在。

ComponentConstructorOptions

在 Svelte 4 中,组件是类。在 Svelte 5 中,它们是函数。 请使用 mount 实例化组件。 有关更多信息,请参见 迁移指南

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

ComponentEvents

Component 类型没有专门的 Events 类型。请使用 ComponentProps 替代。

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

ComponentInternals

在不同环境中变化的内部实现细节

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

ComponentProps

用于获取指定组件所需 props 的便捷类型。

示例:确保一个变量包含 MyComponent 期望的 props:

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

Convenience type to get the props the given component expects.

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

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

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

In Svelte 4, you would do ComponentProps&#x3C;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&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
} from 'svelte';
import
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: LegacyComponentType
MyComponent
from './MyComponent.svelte';
// 如果这些不是 `MyComponent` 期望的正确 props,则会出现错误。 const const props: Record<string, any>props: type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props extends Record<string, any>, any, any> ? Props : Comp extends Component<infer Props extends Record<...>, any, string> ? Props : never

Convenience type to get the props the given component expects.

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

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

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

In Svelte 4, you would do ComponentProps&#x3C;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&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

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

在 Svelte 4 中,你需要使用 ComponentProps<MyComponent>,因为 MyComponent 是一个类。

示例:接受某个组件并推断其 props 类型的泛型函数:

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

Can be used to create strongly typed Svelte components.

Example:

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

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

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

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

Convenience type to get the props the given component expects.

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

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

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

In Svelte 4, you would do ComponentProps&#x3C;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&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
} from 'svelte';
import
type MyComponent = SvelteComponent<Record<string, any>, any, any>
const MyComponent: 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&#x3C;{ foo: string }> {}

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

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

Convenience type to get the props the given component expects.

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

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

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

In Svelte 4, you would do ComponentProps&#x3C;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&#x3C;TComponent extends Component&#x3C;any>>(
	component: TComponent,
	props: ComponentProps&#x3C;TComponent>
) {};

// Errors if the second argument is not the correct props expected by the component in the first argument.
withProps(MyComponent, { foo: 'bar' });
ComponentProps
<function (type parameter) TComponent in withProps<TComponent extends Component<any>>(component: TComponent, props: ComponentProps<TComponent>): voidTComponent>
) {} // 如果第二个参数不是第一个参数中组件期望的正确 props,则会出现错误。 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

此类型已过时,使用新的 Component 类型。

type ComponentType<
	Comp extends SvelteComponent = SvelteComponent
> = (new (
	options: ComponentConstructorOptions<
		Comp extends SvelteComponent<infer Props>
			? Props
			: Record<string, any>
	>
) => Comp) & {
	/** 组件的自定义元素版本。仅在使用 `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;

MountOptions

定义 mount() 函数接受的选项。

type MountOptions<
	Props extends Record<string, any> = Record<string, any>
> = {
	/**
	 * 组件将挂载的目标元素。
	 */
	target: Document | Element | ShadowRoot;
	/**
	 * `target` 中的可选节点。当指定时,它用于在其之前立即渲染组件。
	 */
	anchor?: Node;
	/**
	 * 允许指定事件。
	 * @deprecated 请使用回调 props 替代。
	 */
	events?: Record<string, (e: any) => any>;
	/**
	 * 可以在组件级别通过 `getContext()` 访问。
	 */
	context?: Map<any, any>;
	/**
	 * 是否在初始渲染时播放过渡。
	 * @default true
	 */
	intro?: boolean;
} & ({} extends Props
	? {
			/**
			 * 组件属性。
			 */
			props?: Props;
		}
	: {
			/**
			 * 组件属性。
			 */
			props: Props;
		});

Snippet

#snippet 块的类型。你可以用它来(例如)表示你的组件需要某种类型的代码片段:

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

Declares the props that a component accepts. Example:

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

https://svelte.dev/docs/svelte/$props

$props
();

你只能通过 {@render ...} 标签调用代码片段。

/docs/svelte/snippet

interface Snippet<Parameters extends unknown[] = []> {}
(
	this: void,
	// 这个条件允许元组但不允许数组。数组将表示 rest 参数类型,这是不支持的。如果将来添加了 rest 参数,可以删除该条件。
	...args: number extends Parameters['length'] ? never : Parameters
): {
	'{@render ...} 必须与 Snippet 一起调用': "import type { Snippet } from 'svelte'";
} & typeof SnippetReturn;

在 GitHub 编辑此页面

上一页 下一页