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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27089452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:33:31  来源:igfitidea点击:

How to remove TypeScript warning: property 'length' does not exist on type '{}'

typescriptmultidimensional-array

提问by RaelB

In a TypeScript file, I have defined a 3D array:

在 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);
}

I get a warning under the length property:

我在 length 属性下收到警告:

Property 'length' does not exist on type '{}'

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

Is there something I can do to remove this warning?

我能做些什么来消除这个警告吗?

采纳答案by Ryan Cavanaugh

Option 1: upgrade to bleeding-edge compiler and get union types

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

Option 2: Add a type annotation to the variable declaration:

选项 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);
}

回答by RaelB

I read a similar post here: How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

我在这里阅读了类似的帖子: How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

Which explains that I can cast to <any>.

这解释了我可以转换为 <any>。

This worked for me:

这对我有用:

function testArray(){
    console.log((<any>myArr[1]).length);
}

回答by RamTn

i faced this error before,you have to cast the type to any and when you use generics you have to extends.

我之前遇到过这个错误,你必须将类型转换为 any ,当你使用泛型时,你必须扩展。

check the example blow:

检查示例打击:

const result = <T extends any>(arr:T[]):T => {
  return arr[arr.length - 1] 
}

result([1,2,3])