-2

How to check the value of a number?

for(var index in this.choicesDM) {
  if(index == 0) {
    this.currentChoice = this.choicesDM[index]
  }
}

Here I get the error as mentioned in the title of the question. I also tried to explicitly define the type of index. But didn't work. Found this link but didn't got the solution.

Apogee
  • 689
  • 8
  • 19

2 Answers2

2

In JavaScript (and thus, TypeScript), the in operator returns a string. This is because for in loops iterate over an object's keys, which are strings in JavaScript/TypeScript. So, when you compare index == 0, index is a string and 0 is an integer, thus the error.

Note what I said before, though, that for in enumerates over an object's properties. In the case of arrays, this also includes things like the length property, so it's generally a bad idea to loop over arrays with for in. What you might want instead is a for of loop, where of gives you the value of each object in the array.

Michael Hulet
  • 3,253
  • 1
  • 16
  • 33
1

The reason for this is because == and other related comparison operators operate on operands with same type or type of 1 operand should be subtype of other operand. But in your case 0 is integer and "index" is string. Hence the error.

jat
  • 106
  • 1
  • 8