Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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:

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

Is there something I can do to remove this warning?

like image 652
RaelB Avatar asked Nov 23 '14 13:11

RaelB


People also ask

How do you fix property does not exist on type?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.

Does not exist on type never []?

The error "Property does not exist on type 'never'" occurs when we forget to type a state array or don't type the return value of the useRef hook. To solve the error, use a generic to explicitly type the state array or the ref value in your React application.


2 Answers

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

Which explains that I can cast to <any>.

This worked for me:

function testArray(){     console.log((<any>myArr[1]).length); } 
like image 182
RaelB Avatar answered Oct 07 '22 15:10

RaelB


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

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

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); } 
like image 40
Ryan Cavanaugh Avatar answered Oct 07 '22 14:10

Ryan Cavanaugh