React and Types

Fabio Biondi
Google Expert | Angular
# Typing State
We now create a User
type that we use to type the state value using the useState<User>
syntax.
In this way only objects that respect that type can be saved in the state.
So let's create an example where the state is initialized with { id: 1, name: 'Fabio' }
and we update it when the button is clicked invoking the updateName
function:
useState use generics
When you see a syntax similar to this <Type>
it means that we are using a more advanced TypeScript concept known as Generics Parameters.
Currently, it is only important to understand that this syntax allows us to type our state.
We will cover this topic in more detail in
several chapters of the book.
Here you can see how TypeScript notifies us of an error when we set a new state with a missing property, i.e. name
:
And here a compiler error when one of the properties contains a wrong type (i.e. a number
instead of a string
in the name
property):
Accedi a TUTTI I CORSI PREMIUM ad un unico prezzo!