【问题标题】:Angular Typescript type ERROR when using Array.reduce()使用 Array.reduce() 时的 Angular Typescript 类型错误
【发布时间】:2018-09-09 23:19:13
【问题描述】:

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

型号

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的函数中返回一个Ingredient。与result 相同的类型。还要问自己为什么要减少那里的阵列?旨在向数组添加某些内容的方法似乎极不可能将其减少为单个元素。
  • 尝试用private ingredients: any替换private ingredients: Ingredient[]
  • reduce 在没有内部代码块时返回“void”因此错误,我建议还为 reduce 函数的累加器设置一个默认值,这是第二个参数。 IE array#reduce((a,c) => a+c, 0) 其中 0 是累加器的默认值
  • @BalázsÉdes 谢谢,提供return result 时错误消失了。你认为我做这项工作的方式不对吗?我想要一个具有匹配元素的数组减少数量
  • @ufollettu 阅读Array.prototype.reduce 上的文档和示例,我认为您希望它可以做其他事情

标签: javascript arrays angular typescript reduce


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2020-09-15
    • 2020-07-29
    • 2021-04-08
    • 2021-08-30
    相关资源
    最近更新 更多