docs: more docs on TS types (#14065)

* docs: more docs on TS types

and a few related changes/enhancements
closes #13940

* Apply suggestions from code review

* adjust

* Apply suggestions from code review

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

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

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

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/14134/head
Simon H 3 days ago committed by GitHub
parent 00f5b14d40
commit a952860232
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -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`.
```ts
import type { Component, ComponentProps } from 'svelte';
@ -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} />
```
## 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.

@ -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>

Loading…
Cancel
Save