【发布时间】:2021-06-23 06:56:28
【问题描述】:
这是我的接口文件:
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
我正在尝试通过管道变换减少对象数组:
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
return items.reduce((a, b) => a + b[attr], 0);
}
}
在完整的 HTML 中,我希望计算总时间的总和
{{ (delayCount$ | async) | sum:'totalTime'}}
但我有这个错误:
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'.
然后我将参数 attr: string 更改为 attr: keyof ListCount
仍然有这个错误:
error TS2365: Operator '+' cannot be applied to types 'number' and 'string | number'.
和
error TS2532: Object is possibly 'undefined'.
请帮忙
【问题讨论】:
-
为什么
attr不是像transform(items: ListCount[], attr: number): number {这样的数字 -
@er-sho: 因为它是属性名,它的值要被求和。
-
当
totalTime是唯一可以在数组中求和的类型 (number) 时,传递它的目的是什么?以后还会有number类型的其他属性吗? -
@er-sho:属性
totalTime中包含的值是number类型。但在尝试使用obj['totalTime']访问属性的情况下,totalTime是一个字符串。 -
试试
reduce((a:number, b:any)=>....)
标签: arrays angular typescript pipe reduce