Lesson 14. Better hooks with TypeScript 1. Typing local states
The first way TypeScript can improve your code when using hooks is by giving your local states a type.
In some cases, TypeScript can infer the type itself:
const [age, setAge] = useState(10)// Equivalent to:const [age, setAge] = useState<number>(10)
But it isn’t uncommon to start with an empty state and populate it in a
useEffect for instance. So, depending on your TypeScript configuration, you
may have to give an explicit type to include null or undefined values as a
possible state.
const [name, setName] = useState<string | null>(null)
Whether you specify the state’s type explicitly or not, TypeScript will infer
the right type for both the state’s value (name) and its setter (setName).
Of course, if your state is supposed to contain a more complex value, you are free (and encouraged) to specify the full type, for instance by declaring an interface:
interface Person {name: stringage: number}// In the component:const [person, setPerson] = useState<Person | null>(null)