Skip to content

Commit a2bc0f5

Browse files
authored
Add documentation for svelte/elements (#11587)
closes #11451
1 parent dc16668 commit a2bc0f5

File tree

1 file changed

+43
-0
lines changed
  • sites/svelte-5-preview/src/routes/docs/content/01-api

1 file changed

+43
-0
lines changed

sites/svelte-5-preview/src/routes/docs/content/01-api/05-imports.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,46 @@ const result = render(App, {
107107
props: { some: 'property' }
108108
});
109109
```
110+
111+
## `svelte/elements`
112+
113+
Svelte provides built-in [DOM types](https://github.com/sveltejs/svelte/blob/master/packages/svelte/elements.d.ts). A common use case for DOM types is forwarding props to an HTML element. To properly type your props and get full intellisense, your props interface should extend the attributes type for your HTML element:
114+
115+
```svelte
116+
<script lang="ts">
117+
import { HTMLAttributes } from 'svelte/elements';
118+
119+
interface Props extends HTMLAttributes<HTMLDivElement> {
120+
username: string;
121+
}
122+
123+
let { username, ...rest }: Props = $props();
124+
</script>
125+
126+
<div {...rest}>
127+
Hi, {username}!
128+
</div>
129+
```
130+
131+
> You can use `ComponentProps<ImportedComponent>`, if you wish to forward props to forward props to a Svelte component.
132+
133+
Svelte provides a best-effort of all the HTML DOM types that exist. If an attribute is missing from our [type definitions](https://github.com/sveltejs/svelte/blob/master/packages/svelte/elements.d.ts), you are welcome to open an issue and/or a PR fixing it. For experimental attributes, you can augment the existing types locally by creating a `.d.ts` file:
134+
135+
```ts
136+
import { HTMLButtonAttributes } from 'svelte/elements';
137+
138+
declare module 'svelte/elements' {
139+
export interface SvelteHTMLElements {
140+
'custom-button': HTMLButtonAttributes;
141+
}
142+
143+
// allows for more granular control over what element to add the typings to
144+
export interface HTMLButtonAttributes {
145+
veryexperimentalattribute?: string;
146+
}
147+
}
148+
149+
export {}; // ensure this is not an ambient module, else types will be overridden instead of augmented
150+
```
151+
152+
The `.d.ts` file must be included in your `tsconfig.json` file. If you are using the standard `"include": ["src/**/*"]`, this just means the file should be placed in the `src` directory.

0 commit comments

Comments
 (0)