A Reasonable Solution: Create an Abstraction

Learn how to create the abstraction to solve the type safety problem.

Assuming we aim to maintain integrity with TypeScript and avoid repeating the difficulties experienced during the creation of the previous example, it is possible to achieve both objectives. However, this will require some additional effort.

Instead of checking whether the context is defined every time we use it, we could create our utilities to do this. This will involve a little bit of upfront work, but—unlike the previous solution—once we have our abstractions, we’ll never have to think about them again.

Creating our createContext

Let’s start by making a new file called src/create-context.tsx. We will begin with a simple function to prevent TypeScript from flagging the file as empty:

Get hands-on with 1200+ tech skills courses.