Angular 使用 Array.reduce() 时打字稿类型错误

Angular Typescript type ERROR when using Array.reduce()

假设我有两个类型对象数组(相同类型),我想合并它们,检查一个对象是否已经存在,然后将旧的和新的数量相加,return 一个新数组更新值

型号:

class Ingredient {
  constructor(public name: string, public amount: number){ }
}

数组

  private ingredients: Ingredient[] = [
    new Ingredient('farina', 500),
    new Ingredient('burro', 80),
    new Ingredient('uccellini', 5)
  ];

  private newIngredients: Ingredient[] = [
    new Ingredient('uova', 5),
    new Ingredient('pancetta', 80),
    new Ingredient('uccellini', 8)
  ];

当我尝试创建一个 方法 来检查和合并数组时,我在开始编写代码之前记录了一个错误!:

addIngredients(newIngredients: Ingredient[]) {

  this.ingredients
    .concat(this.newIngredients)
    .reduce((result, curr) => {

    });
}

这是错误

error TS2345: Argument of type '(result: Ingredient, curr: Ingredient) => 
void' is not assignable to parameter of type 
'(previousValue: Ingredient, currentValue: Ingredient, currentIndex: number, array: Ingredient[]) ...'.
Type 'void' is not assignable to type 'Ingredient'.

我无法继续前进,请帮助我!

在您的 .reduce 方法中,return result 错误将消失。