这是因为
我创建了一个转换管道来减少对象的列表
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);
}
}
如HTN答案中所述,使用attr: keyof ListCount
会收紧attr
参数的键入,但由于ListCount
同时具有string
和number
值属性,因此需要使用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);
}
}