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



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

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同时具有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);
}
}

最新更新