打字稿。如何在 foreach 循环中避免此错误:“算术运算的左侧必须是‘any’、‘number’或枚举类型”?

Dan*_*tos 8 javascript foreach compiler-errors typescript

这是 javascript 或 typescript foreach 的一个非常常见的用法:

myArray = ["a","b","c"]

for(var index in myArray)
    console.log(myArray[index]) 
Run Code Online (Sandbox Code Playgroud)

代码日志:ab 和 c

但是在打字稿中,“索引”var 被认为是一个字符串。. 当我进行任何计算时,例如 index*2,TS 编译器会显示空闲编译器错误:

for(var index in myArray)
    console.log(index * 2); // TS compiler error.
Run Code Online (Sandbox Code Playgroud)

错误 TS2362 算术运算的左侧必须是“any”、“number”或枚举类型

但在执行时记录 0,2 和 4(如预期)

如何避免或抑制此错误?

Mik*_*uck 9

index是一个字符串。for..in迭代对象的键。碰巧数组的键是数字的。尽管如此,它们仍以字符串形式存储。

看一下这个:

var myArray = [1, 2, 3];
for (var index in myArray) {
  console.log(typeof index);
}
Run Code Online (Sandbox Code Playgroud)

还值得注意的是,无法保证您将获得这些密钥的顺序。通常,它们会以正确的顺序出现,但"3", "1", "2"例如,您获取 不会无效。

相反,只需使用普通for循环即可。然后你的索引将是数字,你会确定你正在按顺序移动数组。

var myArray = [1, 2, 3];
for (var i = 0; i < myArray.length; i++) {
  console.log(typeof i, myArray[i]);
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用forEach.

var myArray = [1, 2, 3];
myArray.forEach(function(val, index) {
  console.log(typeof index, val);
});
Run Code Online (Sandbox Code Playgroud)