23

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.

3
  • 2
    You should be using an object, not an array. Commented Mar 31, 2013 at 20:44
  • Is "index" a string or an actual numeric index? Commented Mar 31, 2013 at 20:50
  • a string. I guess that I'll do as SLaks said, i thought that typescript arrays can be used a associative arrays as well. Commented Mar 31, 2013 at 20:57

4 Answers 4

34

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

2 Comments

Is there a opposite of the operator in ?
logical, if (!("someKey" in someObject))
11

jsFiddle Demo

Use hasOwnProperty like this:

var a = [];
if( a.hasOwnProperty("index") ){
 /* do something */  
}

2 Comments

Maybe better use hasOwnProperty as Object.prototype.hasOwnProperty.call(a, 'index') neat explanation here
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.
2

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

1 Comment

!! is redundant here. Also, consider the arrays [0, 1, 2] and [false, false].
1

You can also use the findindex method :

var someArray = [];

if( someArray.findIndex(x => x === "index") >= 0) {
    // foud someArray element equals to "index"
}

1 Comment

here x is nothing but whole object inside a array. So how this would help?

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.