'How to iterate in a union type array in angular template

I am new to angular and started working on version 12 and I am stuck in a point. Where I want to iterate in my union array in the template but it gives me error.

Error: Type 'IBasketItem[] | IOrderItem[]' is not assignable to type 'NgIterable'.

this is my union array in the component on which I want to iterate.

@Input() items: IBasketItem[] | IOrderItem[] = [];

this is the template code

<tr *ngFor="let item of items" class="border-0">

it gives me a red line under the ' of ' keyword with above mentioned error

here is the IBasketItem interface

export interface IBasketItem {
id: number;
productName: string;
price: number;
quantity: number;
pictureUrl: string;
brand: string;
type: string;

}

and this is the IOrderItem interface

export interface IOrderItem {
productId: number;
productName: string;
pictureUrl: string;
price: number;
quantity: number;

}

I will be thankful if someone suggest a solution.



Solution 1:[1]

Declare array of type like this @Input() items: [IBasketItem | IOrderItem] = [];

This is iterable then.

OR this way

@Input() items: Array<IBasketItem | IOrderItem> = [];

Solution 2:[2]

Angular checks the expressions and bindings within the templates in the application code. Try setting "strictTemplates": false in tsconfig.json file and you should be fine.

Solution 3:[3]

while @Hitech answer might work, what you are trying to do is a bit sketchy. You will have to check if you have the 'brand' or 'type' property available and then display them or have different logic for an orderItem or for a basketItem.

I recommend you have a common interface for both of them and then iterate through that array:

export interface IItem {
    id: number;
    productName: string;
    price: number;
    quantity: number;
    pictureUrl: string;
}

export interface IOrderItem extends IItem {
    productId: number; // might be the same with the id from the base class, depending on your logic
}

export interface IBasketItem extends IItem {
    brand: string;
    type: string;
}

@Input() items: IItem[] = [];

or have two separate arrays for this and have a for loop for each of them.

@Input() basketItems: IBasketItem [] = [];
@Input() odredItems: IOrderItem [] = [];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hitech Hitesh
Solution 2 John Bull
Solution 3 ursaciuc