0

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

1 Answer 1

1

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[])[]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, no complaints from TS now. I didn't know that I can wrap them in array this way, I appreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.