22

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.

Eduard
  • 8,437
  • 10
  • 42
  • 64
gipouf
  • 1,221
  • 3
  • 15
  • 43

4 Answers4

33

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
}
metadept
  • 7,831
  • 2
  • 18
  • 25
11

jsFiddle Demo

Use hasOwnProperty like this:

var a = [];
if( a.hasOwnProperty("index") ){
 /* do something */  
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • Maybe better use hasOwnProperty as `Object.prototype.hasOwnProperty.call(a, 'index')` neat explanation [here](https://stackoverflow.com/a/12017703/3848267) – Rodrigo García Aug 13 '18 at 19:43
  • It's true, there are ways that the hasOwnProperty could have been abused. If you are making some sort of largely portable library, it may make sense to cover all bases like that. In general though, this works just fine. – Travis J Aug 13 '18 at 20:29
3

One line validation. The simplest way.

if(!!currentData[index]){
  // do something
}

Outputs

var testArray = ["a","b","c"]

testArray[5]; //output => undefined
testArray[1]; //output => "b"

!!testArray[5]; //output => false
!!testArray[1]; //output => true
Raphael Soares
  • 482
  • 6
  • 8
2

You can also use the findindex method :

var someArray = [];

if( someArray.findIndex(x => x === "index") >= 0) {
    // foud someArray element equals to "index"
}
abahet
  • 10,355
  • 4
  • 32
  • 23