Skip to content

Commit b84b468

Browse files
secretsuperstar11090Armaan025
authored andcommitted
add type assertion for useState thanks @priscilaandreani
closes typescript-cheatsheets/react#403
1 parent e72a7ca commit b84b468

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Diff for: docs/basic/getting-started/hooks.md

+12-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Hooks are [supported in `@types/react` from v16.8 up](https://github.com/Definit
77

88
## useState
99

10-
Type inference works very well most of the time:
10+
Type inference works very well for simple values:
1111

1212
```tsx
1313
const [val, toggle] = React.useState(false);
@@ -22,10 +22,21 @@ However, many hooks are initialized with null-ish default values, and you may wo
2222
```tsx
2323
const [user, setUser] = React.useState<IUser | null>(null);
2424

25+
// later...
26+
setUser(newUser);
27+
```
28+
29+
You can also use type assertions if a state is initialized soon after setup and always has a value after:
30+
31+
```tsx
32+
const [user, setUser] = React.useState<IUser>({} as IUser);
33+
2534
// later...
2635
setUser(newUser);
2736
```
2837

38+
This temporarily "lies" to the TypeScript compiler that `{}` is of type `IUser`. You should follow up by setting the `user` state — if you don't, the rest of your code may rely on the fact that `user` is of type `IUser` and that may lead to runtime errors.
39+
2940
## useReducer
3041

3142
You can use [Discriminated Unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions) for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.

0 commit comments

Comments
 (0)