Home > Software design >  Define an array that can has arrays and objects in it
Define an array that can has arrays and objects in it

Time:10-06

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[]'.

CodePudding user response:

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.

CodePudding user response:

filteredData in filteredData as IMenuItemType & IMenuItemType[] will always be an array no matter if it is empty. So replace filteredData as IMenuItemType & IMenuItemType[] with filteredData as IMenuItemType[]

  • Related