使用 Array.reduce() 时的 Angular Typescript 类型错误

ufo*_*ttu 3 javascript arrays reduce typescript angular

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

型号

class Ingredient {
  constructor(public name: string, public amount: number){ }
}
Run Code Online (Sandbox Code Playgroud)

数组

  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)
  ];
Run Code Online (Sandbox Code Playgroud)

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

addIngredients(newIngredients: Ingredient[]) {

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

    });
}
Run Code Online (Sandbox Code Playgroud)

这是错误

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'.
Run Code Online (Sandbox Code Playgroud)

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

eos*_*erg 7

在你的.reduce方法中,返回result,错误就会消失。