Accessing property of nested array error with Element implicitly has an 'any' type because expression of type

Viewed 22

I'm learning TypeScript.

Playing with types I got stuck trying to resolve the following error:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'number | (number | number[])[]'. Property '0' does not exist on type 'number | (number | number[])[]'.

Here is my code

let arr = [2, [22, [222]], 2222];

console.log(arr[1][0]); // 22

I searched around and found examples for objects but I don't know how to do it with a nested array.

How to fix this?

Thanks.

1 Answers

The error makes a lot of sense since the typesystem is not certain that the index arr[1] you are accessing is definitely an array. It could equally be likely the arr[1] is actually a number.

This is the exact advantage typesript gives you. In plain javascript you could write arr[0][1] and you would have no compilation error. You would, however, get a nasty error at runtime since arr[0] is not an array at all.

You should only be able to use arr[1] as an array type after ensuring arr[1] is actually an array. So you must do something like:

if (Array.isArray(arr[1])) {
  console.log(arr[1][0]); // 22 - No typescript error
}
Related