Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TS Errors when declaring types on useContext Provider

I am having difficulty satisfying TS when setting up a useContext state provider

Here I define the interface

interface UserProvider {
  user: UserWithDetails | null
  setUser: React.Dispatch<React.SetStateAction<UserWithDetails>> | null
}
export const UserContext = createContext<UserProvider | {}>({})

Here I pass my values:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<UserContext.Provider value={{ user, setUser }}>

When trying to access my user in a component I receive the TS Error:

Property 'user' does not exist on type '{} | UserProvider'.

const { user } = useContext(UserContext) // Property 'user' does not exist on type '{} | UserProvider'.

How can I resolve this?

>Solution :

Since your Context‘s type is UserProvider | {}, you can’t be sure that user always exists when you use the context. One way to handle this is to use null instead and do a null check.

interface UserProvider {
  // your user provider
}
const UserContext = createContext<UserProvider | null>(null)

export const useUser = () => {
  const context = useContext(UserContext);

  // At this point, you don't know if your context is null or UserProvider

  if (context === null) {
    throw new Error("UserContext not provided");
  }

  // At this point, you know that your context has to be UserProvider

  return context;
};

Now, in your consumer, you can just consume the useUser hook instead of using the UserContext directly. This helps you to avoid null checks in your component.

// const { user } = useContext(UserContext)
const { user } = useUser()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading