Sometimes the initial value of the state can be null or undefined.
This is very often the case when data is loaded from the server via a REST API, so that initially the data is not available and will later arrive asynchronously.
We simulate now this scenario initializing the state with null and populating it after a click of a button.
So the state is now typed as User | null since can potentially contains both types.
The | symbol defines a new type using an union type: in short it means this state is typed to contain a User object ornull.
App.tsx
Result
This component will generate a runtime error at the first render as it will try to render the user.id and user.name properties of an object that is currently null and contains nothing
TypeScript can warn you if an object is potentially null or undefined and will block you in the build phase with a compiler error.
This error tells you that you cannot use the property safely because the object may not exist blocking your build from going into production with this code.
In other words, TypeScript warns you to handle this scenario by inserting controls.
This option is part of the TypeScript rules set known as Strict Mode that can be enabled from the TypeScript configuration file present in each project, usually called tsconfig.json:
Strict Mode is a set of rules that are all enabled by default when set to true.
However it is also possible to enable or disable individual rules and in this case we have used the rule strictNullChecks
Today almost all frameworks and front-end libraries enable the strict mode option by default