You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation/docs/07-misc/03-typescript.md
+21-5Lines changed: 21 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -130,6 +130,22 @@ Components can declare a generic relationship between their properties. One exam
130
130
131
131
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.
132
132
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
+
133
149
## Typing `$state`
134
150
135
151
You can type `$state` like any other variable.
@@ -159,9 +175,9 @@ class Counter {
159
175
160
176
## The `Component` type
161
177
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.
163
179
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:
165
181
166
182
```svelte
167
183
<script lang="ts">
@@ -170,13 +186,13 @@ Using it together with `<svelte:component>` to restrict what kinds of component
170
186
interface Props {
171
187
// only components that have at most the "prop"
172
188
// property required can be passed
173
-
component: Component<{ prop: string }>;
189
+
DynamicComponent: Component<{ prop: string }>;
174
190
}
175
191
176
-
let { component }: Props = $props();
192
+
let { DynamicComponent }: Props = $props();
177
193
</script>
178
194
179
-
<svelte:component this={component} prop="foo" />
195
+
<DynamicComponent prop="foo" />
180
196
```
181
197
182
198
Closely related to the `Component` type is the `ComponentProps` type which extracts the properties a component expects.
0 commit comments