Home > Enterprise >  Argument of type 'any' is not assignable to parameter of type 'never'.ts(2345)
Argument of type 'any' is not assignable to parameter of type 'never'.ts(2345)

Time:12-27

I get an error when trying to add a Cart Item object to the foods array.

Argument of type 'any' is not assignable to parameter of type 'never'.ts(2345)

I understand that the problem is that foods is declared without specifying the type.

foods: []

How to solve this problem?

export class CartService {

  items$: CartItem[] = [];

  constructor() {
    this.items$ = [];
  }

  getItemsInCart() {
    return this.items$;
  }

}

export class CartItem {
    quantity = 1; 
    food: any;  
    constructor(food: any) {
      this.food = food;
    }  
}


export class CartComponent implements OnInit {

  model = {
    Name: '',
    State: '',
    foods: []
  };

  constructor(private cart: CartService) {

  }
  ngOnInit() {}
  onSubmit() {
    this.cart.getItemsInCart().forEach(cartItem => {
      this.model.foods.push(cartItem.food);
    });
  }
}  

CodePudding user response:

Try to specify the type of foods in model :

  model = {
    Name: '',
    State: '',
    foods: [] as any[]
  };
  • Related