【发布时间】:2018-03-29 19:38:47
【问题描述】:
我有这个代码块:
function sumOnValue<T, K extends keyof T>(collection: Array<T>, key: K): number {
let result = 0;
for (const o of collection) {
const sample = o[key];
if (typeof o[key] === 'number') {
result = result + sample; // [ts] Operator '+' cannot be applied to types 'number' and 'T[K]'. red squigly line under sample.
}
}
return result;
}
const sampleCharges: Array<ICharge> = [
{
AllowedAmount: 10,
},
{
AllowedAmount: 15,
},
{
AllowedAmount: 9,
},
];
const resultedSum = sumOnValue(sampleCharges, 'AllowedAmount');
console.log(resultedSum);
如上所示,我从编译器收到错误(vscode 将其报告为问题),但是在运行代码时它很好并且没有抱怨。我应该在这里做什么来抑制错误或“通过类型检查安全地”编写此方法?
简而言之,目标是: 将T 数组中的给定属性相加,前提是给定属性是T 中的一个类型,并且该属性是一个数字。
【问题讨论】:
标签: typescript