Search code examples
reactjstypescriptreact-context

How to define type in a array of context in react


I have a context:

export const templateContext = createContext({
  isButtonDisable: true,
  setIsButtonDisable: (p: boolean) => {},
  isSubmitReady: <boolean>false,
  setIsSubmitReady: () => {},
  buttonShow: false,
  handleButtonShow: (val: boolean) => {},
  steps:  [] ,
  handleSteps: (val: never) => {},
});

I am not understanding How can I define the type of array in this context. especially the steps array. That array also contains object


Solution

  • You need to add a type for your object first, e.g.:

    type MyContext = {
      isButtonDisable: boolean;
      setIsButtonDisable: (p: boolean) => {};
      // and so on //
      steps: String[];
    };
    

    If array is complex, you should create a separate type for it as well. For example, you array contains an array of Step objects:

    type Step = {
      id: string;
      value: number;
    };
    

    So now you can modify your MyContext:

    type MyContext = {
      isButtonDisable: boolean;
      setIsButtonDisable: (p: boolean) => {};
      // and so on //
      steps: Step[];
    };