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

Type inference error when creating a React Context

I’m trying to create simple context provider in a project that uses TypeScript, typed as such:

import { createContext } from 'react';

export type ContextType = {
  foo: boolean,
};

export const FooContext: React.Context<ContextType> = createContext({
  foo: true,
});

It looks simple enough, but on FooContext TypeScript is telling me that Type 'Context<{ loading: true; }>' is not assignable to type 'Context<ContextType>'. becasuse Type 'boolean' is not assignable to type 'true'.

Casting foo: true as boolean fixes the issue, but I think it’s strange that that’s even necessary.

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

Is there any other way to do this correctly without getting any type errors?

>Solution :

You should pass your context type as a type parameter instead:

export const FooContext = createContext<ContextType>({
    foo: true,
});

FooContext will be inferred to be the type React.Context<ContextType>.

Playground

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