0

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
  • 2
    You have to check if it's an array before indexing into it. Commented Sep 16, 2022 at 20:43

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

This seem to work for me.

Before Error:

const slug = props.data[0].attributes.slug;

After adding check "Array.isArray":

const slug = Array.isArray(props.data) ? props.data[0].attributes.slug : null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.