如何删除TypeScript警告:类型"{}"上不存在属性"length"

Rae*_*elB 6 multidimensional-array typescript

在TypeScript文件中,我定义了一个3D数组:

var myArr = ['one', [[19, 1], [13, 1], [86, 1], [12, 2]],
             'two',    [[83, 1], [72, 1], [16, 2]],
             'three',  [[4, 1]]];

function testArray(){
    console.log(myArr[1].length);
}
Run Code Online (Sandbox Code Playgroud)

我在长度属性下收到警告:

类型"{}"上不存在属性"长度"

我有什么办法可以删除此警告吗?

Rae*_*elB 15

我在这里阅读了类似的帖子: 在使用Typescript时,如何停止"类型JQuery上不存在属性"语法错误?

这说明我可以投射到<any>.

这对我有用:

function testArray(){
    console.log((<any>myArr[1]).length);
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*ugh 9

选项 1:升级到前沿编译器并获得联合类型

选项 2:在变量声明中添加类型注释:

var myArr: any[] = ['one', [[19, 1], [13, 1], [86, 1], [12, 2]],
             'two',    [[83, 1], [72, 1], [16, 2]],
             'three',  [[4, 1]]];

function testArray(){
    console.log(myArr[1].length);
}
Run Code Online (Sandbox Code Playgroud)


小智 8

Object.values() 方法返回给定对象自己的可枚举属性值的数组,其顺序与 for...in 循环提供的顺序相同。(唯一的区别是 for...in 循环也枚举原型链中的属性。)

Object.values(myArr).length
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values