Type Safety Problem While Using TypeScript with React
Learn about the type safety problem of TypeScript and some solutions to it.
We'll cover the following
The fundamental problem
The core issue on our side is not necessarily a TypeScript problem. It’s a React problem:
When we call
React.createContext
, TypeScript will want to know what value we can expect.But we don’t have that value yet because we have to wait for the
Provider
component to mount to useuseState
.TypeScript will consider this an issue because we’re passing it something that isn’t what it expects.
If we say it can be a color or
undefined
, TypeScript will never be sure which one it’s working with.
We’ll consider a few approaches—such as using any
or undefined
—which will work but have some trade-offs before we settle on a better (though more involved) solution.
A rejected solution: Use any
In the code below, we glimpse an easier possible solution. We can just completely opt out of TypeScript by using any
. Not only will we lose the type safety that comes with that, but we’ll also lose all of the benefits of autocomplete in our code. This works, but we can do better.
Get hands-on with 1200+ tech skills courses.