'How to remove TypeScript warning: property 'length' does not exist on type '{}'
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?
Solution 1:[1]
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);
}
Solution 2:[2]
i faced this error before,you have to cast the type to any and when you use generics you have to extends.
check the example blow:
const result = <T extends any>(arr:T[]):T => {
return arr[arr.length - 1]
}
result([1,2,3])
Solution 3:[3]
for those who already have a interface/type/class configured and would like it to have a length or something else i have a suggestion that i use. Inside the class, interface, type put the code below. It will set unknown only on undefined attributes. It is not necessary to put it at the end, I also suggest that you create a separate interface and extend it to your objects if you prefer
export interface x {
...
[props: string]: unknown
...
}
This will make it possible for you to use any attribute name in your object, as bad as it sounds, it actually isn't. That's because for each unknown attribute you will be forced(T.S 4.4+) to do a forced conversion to some other type when you use, eg
(object.length as number).
When analyzing the possible type of the attribute you will be more careful and will not try to access something that does not exist. Don't worry about your object auto-completion, it will keep working normally
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | RamTn |
| Solution 3 | Mithsew |
