【发布时间】:2021-05-28 00:43:43
【问题描述】:
当有这样的类型时,即使在执行数组操作之前检查tyepof,我也无法执行数组操作:
type Demo = {
[countryName: string]: number | Array<number>
}
我不得不使用as number 并根据需要创建尽可能多的时间变量。
这是一个简化的示例,但它可能会变得非常难看:
Playground reproduction
var countries:Demo = {
'spain': 0,
'italy': 20,
'germany': [0, 1, 2]
};
var total: number = 0;
for (var country in countries) {
if(typeof countries[country] === "number"){ //<--- useless?
total += countries[country] as number; // forced to use it
}
else{
var tmpCountries = countries[country] as Array<number>; //<--- forced tmp variable
for(let i = 0; i<tmpCountries.length; i++){
total += countries[country] as number; //<-- again as number?
}
}
}
在我们的代码中,我们希望根据条件对其应用数字运算和数组运算的这种对象的处理方式是什么?
【问题讨论】:
-
TS 不喜欢你只是重复使用同一个索引。在这种情况下,它不会保持类型缩小。您需要一个变量,它可以在循环开始时像
const c = countries[country]一样简单,因此您只需使用一个变量而不是一遍又一遍地索引。可能更简单的选择是直接循环对象的值:for (var country of Object.values(countries))(注意for..ofloop) -
另外,建议不要使用
var。在 TS 中不需要 - 它会编译const或let到适当的形式。 -
查看the question this duplicates的答案;这里推荐的解决方法是将值保存到现在可以进行控制流分析的新变量中,例如this(啊,我看到@VLAZ 刚刚说过)。
-
@jcalz Here is using
for..ofover just the object values 只是为了完整性。但都是一样的,只是在循环中省去了声明变量的一行。
标签: typescript