Type inference error when creating a React Context

Advertisements

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.

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

Leave a ReplyCancel reply