Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Typescript中使用数组解构而不出错?_Typescript - Fatal编程技术网

如何在Typescript中使用数组解构而不出错?

如何在Typescript中使用数组解构而不出错?,typescript,Typescript,我用Typescript编写了一些代码: for (const [a, b] of [['1', 2],['3', 4]]) { console.log(a.substr(0)); } 在javascript中,它工作并输出: 1 3 但在Typescript中,这将导致substr附近的编译错误: TS2339: Property 'substr' does not exist on type 'string | number'.   Property 'substr' does no

我用Typescript编写了一些代码:

for (const [a, b] of [['1', 2],['3', 4]]) {
  console.log(a.substr(0));
}
在javascript中,它工作并输出:

1
3
但在Typescript中,这将导致
substr
附近的编译错误:

TS2339: Property 'substr' does not exist on type 'string | number'.   Property 'substr' does not exist on type 'number'.
编译器似乎无法根据字符串/数字确认a的类型


我认为这是一个打字错误。我错了吗?或者是否有更好的方法来实现这一点?

这不是一个bug。基本上,当您编写
['1',2]
时,Typescript会将其理解为
[]
,而不是
[string,number]
。因此,如果要将其强制为[number,string],则必须定义类型

  for (const [a, b] of <[string, number][]>[['1', 2],['3', 4]]) {
    console.log(a.substr(0));
  }
[1',2],[3',4]]的常数[a,b]{ console.log(a.substr(0)); }