docs: added generic type parameter example for $state (#18494)

pull/18680/merge
Jared Dunham 4 weeks ago committed by GitHub
parent f5f70343df
commit f4918d86f3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -170,6 +170,12 @@ If you don't give `$state` an initial value, part of its types will be `undefine
let count: number = $state();
```
You can pass the type directly as a generic parameter to safely handle this. TypeScript will infer the variable as `number | undefined`.
```ts
let count = $state<number>();
```
If you know that the variable _will_ be defined before you first use it, use an `as` casting. This is especially useful in the context of classes:
```ts

Loading…
Cancel
Save