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

TypeScript React error when passing to context object

In my project, I have a context provider that is itself an object with multiple properties:

<Provider value={
        {
            scaleNum: scaleNum,                 // number
            scaleLet: scaleLet,                 // string
            scaleSettings: scaleSettings,       // stateful object
            setScaleSettings: setScaleSettings, // statesetter function
            scaleModeOptions: scaleModeOptions  // string array
        }
    }>
        {children}
    </Provider>

When I try to pass this, I get the following type error for scaleSettings (an object)

Type ‘{ scaleNum: number[]; scaleLet: string[]; scaleSettings: { scale: number; mode: number; isSharp: boolean; }; setScaleSettings: React.Dispatch<React.SetStateAction<{ scale: number; mode: number; isSharp: boolean; }>>; scaleModeOptions: string[]; }’ is not assignable to type ‘ScaleContextProviderType’.
Object literal may only specify known properties, and ‘scaleSettings’ does not exist in type ‘ScaleContextProviderType’.ts(2322)
index.d.ts(328, 9): The expected type comes from property ‘value’ which is declared here on type ‘IntrinsicAttributes & ProviderProps’

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

At first I thought maybe React doesn’t want you passing objects within an object, so I tried removing those:

It just moved the same error down. The error seems to occur on whatever is after scaleLet:

Any ideas?

>Solution :

React.createContext is strongly typed in Typescript. You need to define all the properties in the value type nominated

import { Dispatch, SetStateAction } from "react";

type ScaleSettings = /* something */;

interface ScaleContextProviderType {
  scaleNum: number;
  scaleLet: string;
  scaleSettings: ScaleSettings;
  setScaleSettings: Dispatch<SetStateAction<ScaleSettings>>;
  scaleModeOptions: string[];  
}

Dispatch<SetStateAction<ScaleSettings>> is just an easier way to define a function that accepts a ScaleSettings object (or undefined) or a functional update callback.

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