如何在Typescript中使用数组解构而不出错?
我用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
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));
}