Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: more docs on TS types #14065

Merged
merged 9 commits into from
Nov 3, 2024
17 changes: 16 additions & 1 deletion documentation/docs/07-misc/03-typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,9 @@ Using it together with dynamic components to restrict what kinds of component ca
<DynamicComponent prop="foo" />
```

Closely related to the `Component` type is the `ComponentProps` type which extracts the properties a component expects.
> [!LEGACY] In Svelte 4, components were of type `SvelteComponent`

To extract the properties from a component, use `ComponentProps`.
Rich-Harris marked this conversation as resolved.
Show resolved Hide resolved

```ts
import type { Component, ComponentProps } from 'svelte';
Expand All @@ -211,6 +213,19 @@ function withProps<TComponent extends Component<any>>(
withProps(MyComponent, { foo: 'bar' });
```

To declare that a variable expects the constructor or instance type of a component:

```svelte
<script lang="ts">
import MyComponent from './MyComponent.svelte';

let componentConstructor: typeof MyComponent = MyComponent;
let componentInstance: MyComponent;
</script>

<MyComponent bind:this={componentInstance} />
```
Rich-Harris marked this conversation as resolved.
Show resolved Hide resolved

## Enhancing built-in DOM types

Svelte provides a best effort of all the HTML DOM types that exist. Sometimes you may want to use experimental attributes or custom events coming from an action. In these cases, TypeScript will throw a type error, saying that it does not know these types. If it's a non-experimental standard attribute/event, this may very well be a missing typing from our [HTML typings](https://github.com/sveltejs/svelte/blob/main/packages/svelte/elements.d.ts). In that case, you are welcome to open an issue and/or a PR fixing it.
Expand Down
5 changes: 3 additions & 2 deletions documentation/docs/07-misc/07-v5-migration-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -599,13 +599,14 @@ To declare that a component of a certain type is required:

```svelte
<script lang="ts">
import type { Component } from 'svelte';
import type { ---SvelteComponent--- +++Component+++ } from 'svelte';
import {
ComponentA,
ComponentB
} from 'component-library';

let component: Component<{ foo: string }> = $state(
---let component: typeof SvelteComponent<{ foo: string }>---
+++let component: Component<{ foo: string }>+++ = $state(
Math.random() ? ComponentA : ComponentB
);
</script>
Expand Down