Home > Software design >  Typescript: type is object where property names are unknown
Typescript: type is object where property names are unknown

Time:07-19

I am currently making a component in React and one of the properties is called 'initNavData'. This is an object where the property names will always be different names and there are an unknown amount of these properties. Each of them will have the same structure though. How can I create a type for this?

I saw the [x: string] suggestion, but will this allow for an unlimited amount of properties?

interface WizardProps {
  id: string;
  // parentWizard: string
  isSubwizard: boolean;
  wizardName: string;
  initNavData: {
    [x: string]: {
      label: string;
      status: string;
      current: boolean;
      active: boolean;
      icon: string;
      key: string;
    }
  }
}

CodePudding user response:

yeah, you can use index signatures. As TypeScript handbook says:

Sometimes you don’t know all the names of a type’s properties ahead of time, but you do know the shape of the values.

In those cases you can use an index signature to describe the types of possible values

  • Related