Home > database >  TypeScript React error when passing to context object
TypeScript React error when passing to context object

Time:08-19

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'

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?

CodePudding user response:

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.

  • Related