减少错误类型参数管道转换 Angular

Reduce error type param pipe transform Angular

我创建了一个转换管道来减少对象列表

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: string): number {
    return items.reduce((a, b) => a + b[attr], 0);
  }
}

这是 ListCount 的模型:

export interface ListCount {
  centre?: string;
  cause?: string;
  Time?: number;
}

但是我有这个错误:

 error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'

请帮忙

因为attr是一个字符串,所以不是ListCount

的已知属性

你可以试试:

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: keyof ListCount): number {
    return items.reduce((a, b) => a + b[attr], 0);
  }
}

中所述,使用 attr: keyof ListCount 收紧 attr 参数的类型,但因为 ListCount 同时具有 stringnumber 值属性,您需要使用 typeof.

验证您从 b 获得的属性是否属于 number 类型
export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: keyof ListCount): number {
    return items.reduce((a, b) => {
      // get `attr` value from `b`
      const value = b[attr];
      // validate if type of `b[attr]` is number
      // - if so do the addition
      // - otherwise return previous `a` value
      return typeof value === 'number' ? a += value : a;
    }, 0);
  }
}