How to define type in a array of context in react

Asa*_*mel 2 typescript reactjs react-context

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) => {},
});
Run Code Online (Sandbox Code Playgroud)

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

小智 5

您需要首先为您的对象添加类型,例如:

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

如果数组很复杂,您也应该为其创建一个单独的类型。例如,您的数组包含一个Step对象数组:

type Step = {
  id: string;
  value: number;
};
Run Code Online (Sandbox Code Playgroud)

所以现在你可以修改你的MyContext

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

  • 是的,这样做,然后在创建上下文时设置通用,例如 createContext&lt;MyContext&gt;({ (2认同)