Home > Back-end >  Typescript defining a type holds both array of object and arrays
Typescript defining a type holds both array of object and arrays

Time:02-06

I'm trying to figure out how can I define a type of array contains objects array and array or objects keys as elements :

export type iFormInputTest = {
  name: string
  type: 'textInput' | 'Select'
}

export type iFormInputsTest= {
  button: {
    label: string
    style?: { [key: string]: any }
  }
  data: iFormInputTest[] | iFormInputTest[][]
}

const inputs: iFormInputsTest = {
  button: {
    label: 'Submit'
  },
  data: [
    {
      name: 'input1',
      type: 'textInput'
    },
    [
      {
        name: 'input2',
        type: 'textInput'
      },
      {
        name: 'input3',
        type: 'Select'
      }
    ],
    {
      name: 'input4',
      type: 'textInput'
    }
]}

This is the type error I get :

Type '({ name: string; type: "textInput"; } | ({ name: string; type: "textInput"; } | { name: string; type: "Select"; })[])[]' is not assignable to type 'iFormInputTest[] | iFormInputTest[][]'. Type '({ name: string; type: "textInput"; } | ({ name: string; type: "textInput"; } | { name: string; type: "Select"; })[])[]' is not assignable to type 'iFormInputTest[]'. Type '{ name: string; type: "textInput"; } | ({ name: string; type: "textInput"; } | { name: string; type: "Select"; })[]' is not assignable to type 'iFormInputTest'. Type '({ name: string; type: "textInput"; } | { name: string; type: "Select"; })[]' is missing the following properties from type 'iFormInputTest': name, type

I tried everything but I wasn't able to find a way to define a data key holds both array of iFormInputTest objects and recursive array of iFormInputTest

CodePudding user response:

To be honest, I'm not sure about the reason, but it it fixable by declaring the type like this:

export type iFormInputsTest= {
  // ...
  data: Array<iFormInputTest | iFormInputTest[]>
}

-- Edit--

On a second thought, it actually makes sense for it to fail. You have a union type which means that either you have a property which is iFormInputTest[] or your property must be iFormInputTest[][] but not mixed. The way you can mix them is as I stated, having an array of either iFormInputTest or iFormInputTest[].

You can have the same result with this syntax (in case you prefer it):

export type iFormInputsTest= {
  // ...
  data: (iFormInputTest | iFormInputTest[])[]
}
  • Related