Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Typescript type ERROR when using Array.reduce()

let say I have two arrays of typed object (same type), and I want to merge them, checking if an object already exists, then sum the old and new amount and return a new array with updated values

model:

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

arrays:

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

when I try to create a method to check and merge arrays, I have an ERROR logged before to start writing my code!:

addIngredients(newIngredients: Ingredient[]) {

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

    });
}

This is the error:

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

I cannot move on, please help me!

like image 589
ufollettu Avatar asked Nov 26 '25 12:11

ufollettu


1 Answers

In your .reduce method, return result and the error will disappear.

like image 109
eosterberg Avatar answered Nov 28 '25 01:11

eosterberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!