Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define an array that can has arrays and objects in it

I’m working on my project with angular and typescript.
here I defined an array which items can be arrays or objects.

public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = [];

typesOfData.forEach(type => {
      let filteredData: IMenuItemType | IMenuItemType[];

      filteredData = data.filter(el => {
        return el.Type === type;
      });
      if (filteredData.length > 1) {
        this.arrangedFooterMenu.push(filteredData as IMenuItemType & IMenuItemType[]);
      } else {
      // here in else section I get error
        this.arrangedFooterMenu.push(...filteredData);
      }
    });

and getting error on else section’s filtered data, it says.
TS2345: Argument of type ‘IMenuItemType’ is not assignable to parameter of type ‘IMenuItemType & IMenuItemType[]’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

IMenuItemType[][] | IMenuItemType[] means only array of IMenuItemType[]s or only array of IMenuItemType.
If you want to have different type of values in same array, use (IMenuItemType | IMenuItemType[])[]
Also assign initial value to your array to be able to push items in it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading