TypeScript · Junior · Question 24 of 75
How do you specify the state type if the initial value is null: useState(null)?
- ✓Correct answer:
useState<User | null>(null) - 2
useState(null as User) - 3No need to specify it; TS infers
User
Explanation
Without a generic, the type is inferred as null, and you won't be able to assign a user later. An explicit generic describes all possible states. The cast null as User lies to the compiler: the code will then assume a user always exists.