Skip to content
Advertisement

How to check if an array index exist?

I’m trying to check whether an array index exist in TypeScript, by the following way (Just for example):

var someArray = [];

// Fill the array with data

if ("index" in someArray) {
   // Do something
}

However, i’m getting the following compilation error:

The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type

Anybody knows why is that? as far as I know, what I’m trying to do is completely legal by JS.

Thanks.

Advertisement

Answer

As the comments indicated, you’re mixing up arrays and objects. An array can be accessed by numerical indices, while an object can be accessed by string keys. Example:

var someObject = {"someKey":"Some value in object"};

if ("someKey" in someObject) {
    //do stuff with someObject["someKey"]
}

var someArray = ["Some entry in array"];

if (someArray.indexOf("Some entry in array") > -1) {
    //do stuff with array
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement