假设我有两个类型对象数组(相同类型),我想合并它们,检查一个对象是否已经存在,然后将新旧数量相加并返回一个包含更新值的新数组
型号:
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'.
我无法继续前进,请帮助我!
答案 0 :(得分:2)
在.reduce
方法中,返回result
,错误将消失。