A Reasonable Solution: Create an Abstraction
Learn how to create the abstraction to solve the type safety problem.
We'll cover the following...
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:
export const createContext = () => {};
Next, we’ll use React’s createContext
to create a Context
object that we’ll build on top of:
import React from 'react';export const createContext = () => {const Context = React.createContext(null);};
We’ll use React.createContext
as opposed to import { createContext } from 'react';
so that we don’t have any naming collisions. The name of our function isn’t important, but we like consistency.
Now, we’ll do something similar to what we did in the previous example: we’ll acknowledge that we might not know what the initial value is. We’ll also use a ...