Skip to content

Commit 96e2d5a

Browse files
authored
docs: provide info about wrapper components (#13826)
closes #13006
1 parent 5669b31 commit 96e2d5a

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

documentation/docs/07-misc/03-typescript.md

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,22 @@ Components can declare a generic relationship between their properties. One exam
130130

131131
The content of `generics` is what you would put between the `<...>` tags of a generic function. In other words, you can use multiple generics, `extends` and fallback types.
132132

133+
## Typing wrapper components
134+
135+
In case you're writing a component that wraps a native element, you may want to expose all the attributes of underlying element to the user. In that case, use (or extend from) one of the interfaces provided by `svelte/elements`. Here's an example for a `Button` component:
136+
137+
```svelte
138+
<script lang="ts">
139+
import type { HTMLButtonAttributes } from 'svelte/elements';
140+
141+
let { children, ...rest }: HTMLButtonAttributes = $props();
142+
</script>
143+
144+
<button {...rest}>
145+
{@render children()}
146+
</button>
147+
```
148+
133149
## Typing `$state`
134150

135151
You can type `$state` like any other variable.
@@ -159,9 +175,9 @@ class Counter {
159175

160176
## The `Component` type
161177

162-
Svelte components or of type `Component`. You can use it and its related types to express a variety of constraints.
178+
Svelte components are of type `Component`. You can use it and its related types to express a variety of constraints.
163179

164-
Using it together with `<svelte:component>` to restrict what kinds of component can be passed to it:
180+
Using it together with dynamic components to restrict what kinds of component can be passed to it:
165181

166182
```svelte
167183
<script lang="ts">
@@ -170,13 +186,13 @@ Using it together with `<svelte:component>` to restrict what kinds of component
170186
interface Props {
171187
// only components that have at most the "prop"
172188
// property required can be passed
173-
component: Component<{ prop: string }>;
189+
DynamicComponent: Component<{ prop: string }>;
174190
}
175191
176-
let { component }: Props = $props();
192+
let { DynamicComponent }: Props = $props();
177193
</script>
178194
179-
<svelte:component this={component} prop="foo" />
195+
<DynamicComponent prop="foo" />
180196
```
181197

182198
Closely related to the `Component` type is the `ComponentProps` type which extracts the properties a component expects.

0 commit comments

Comments
 (0)