使用Array.reduce()时,Angular Typescript类型为ERROR

时间:2018-03-30 23:01:44

标签: javascript arrays angular typescript reduce

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

型号

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)
  ];

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

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

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

1 个答案:

答案 0 :(得分:2)

.reduce方法中,返回result,错误将消失。