docs: fine-tune $props types info (#12534)

Show how to do optional props, add jsdoc example to non-preview-docs

closes #12528
pull/12540/head
Simon H 5 months ago committed by GitHub
parent 0fb9fb9a95
commit 2698716bdf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -72,13 +72,31 @@ If you're using TypeScript, you can declare the prop types:
```svelte ```svelte
<script lang="ts"> <script lang="ts">
interface Props { interface Props {
a: number; required: string;
b: boolean; optional?: number;
c: string;
[key: string]: unknown; [key: string]: unknown;
} }
let { a, b, c, ...everythingElse }: Props = $props(); let { required, optional, ...everythingElse }: Props = $props();
</script>
```
If you're using JavaScript, you can declare the prop types using JSDoc:
```svelte
<script>
/** @type {{ x: string }} */
let { x } = $props();
// or use @typedef if you want to document the properties:
/**
* @typedef {Object} MyProps
* @property {string} y Some documentation
*/
/** @type {MyProps} */
let { y } = $props();
</script> </script>
``` ```

@ -556,17 +556,22 @@ let props = $props();
If you're using TypeScript, you can declare the prop types: If you're using TypeScript, you can declare the prop types:
<!-- prettier-ignore -->
```ts ```ts
type MyProps = any; interface MyProps {
// ---cut--- required: string;
let { a, b, c, ...everythingElse }: MyProps = $props(); optional?: number;
partOfEverythingElse?: boolean;
};
let { required, optional, ...everythingElse }: MyProps = $props();
``` ```
> In an earlier preview, `$props()` took a type argument. This caused bugs, since in a case like this... > In an earlier preview, `$props()` took a type argument. This caused bugs, since in a case like this...
> >
> ```ts > ```ts
> // @errors: 2558 > // @errors: 2558
> let { x = 42 } = $props<{ x: string }>(); > let { x = 42 } = $props<{ x?: string }>();
> ``` > ```
> >
> ...TypeScript [widens the type](https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwBIAHGHIgZwB4AVeAXnilQE8A+ACgEoAueagbgBQgiCAzwA3vAAe9eABYATPAC+c4qQqUp03uQwwsqAOaqOnIfCsB6a-AB6AfiA) of `x` to be `string | number`, instead of erroring. > ...TypeScript [widens the type](https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwBIAHGHIgZwB4AVeAXnilQE8A+ACgEoAueagbgBQgiCAzwA3vAAe9eABYATPAC+c4qQqUp03uQwwsqAOaqOnIfCsB6a-AB6AfiA) of `x` to be `string | number`, instead of erroring.

Loading…
Cancel
Save