如何在Typescript中使用数组解构且没有错误?

时间:2019-03-11 08:47:34

标签: 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 not exist on type 'number'.

似乎编译器无法从字符串/数字确认a的类型。

我认为这是TypeScript的错误。我错了吗?还是有更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

这不是错误。基本上,当您编写['1', 2]时,Typescript会将其理解为<string | number>[]而不是[string, number]。因此,如果要将其强制为[数字,字符串],则必须定义类型

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