Skip to content

Commit 2698716

Browse files
authored
docs: fine-tune $props types info (#12534)
Show how to do optional props, add jsdoc example to non-preview-docs closes #12528
1 parent 0fb9fb9 commit 2698716

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

documentation/docs/02-template-syntax/01-component-fundamentals.md

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,31 @@ If you're using TypeScript, you can declare the prop types:
7272
```svelte
7373
<script lang="ts">
7474
interface Props {
75-
a: number;
76-
b: boolean;
77-
c: string;
75+
required: string;
76+
optional?: number;
7877
[key: string]: unknown;
7978
}
8079
81-
let { a, b, c, ...everythingElse }: Props = $props();
80+
let { required, optional, ...everythingElse }: Props = $props();
81+
</script>
82+
```
83+
84+
If you're using JavaScript, you can declare the prop types using JSDoc:
85+
86+
```svelte
87+
<script>
88+
/** @type {{ x: string }} */
89+
let { x } = $props();
90+
91+
// or use @typedef if you want to document the properties:
92+
93+
/**
94+
* @typedef {Object} MyProps
95+
* @property {string} y Some documentation
96+
*/
97+
98+
/** @type {MyProps} */
99+
let { y } = $props();
82100
</script>
83101
```
84102

sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -556,17 +556,22 @@ let props = $props();
556556

557557
If you're using TypeScript, you can declare the prop types:
558558

559+
<!-- prettier-ignore -->
559560
```ts
560-
type MyProps = any;
561-
// ---cut---
562-
let { a, b, c, ...everythingElse }: MyProps = $props();
561+
interface MyProps {
562+
required: string;
563+
optional?: number;
564+
partOfEverythingElse?: boolean;
565+
};
566+
567+
let { required, optional, ...everythingElse }: MyProps = $props();
563568
```
564569

565570
> In an earlier preview, `$props()` took a type argument. This caused bugs, since in a case like this...
566571
>
567572
> ```ts
568573
> // @errors: 2558
569-
> let { x = 42 } = $props<{ x: string }>();
574+
> let { x = 42 } = $props<{ x?: string }>();
570575
> ```
571576
>
572577
> ...TypeScript [widens the type](https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwBIAHGHIgZwB4AVeAXnilQE8A+ACgEoAueagbgBQgiCAzwA3vAAe9eABYATPAC+c4qQqUp03uQwwsqAOaqOnIfCsB6a-AB6AfiA) of `x` to be `string | number`, instead of erroring.

0 commit comments

Comments
 (0)