4

This looks like a problem with the typescript compiler, but not sure, maybe I do not understand typescript type inference. Can anybody explain this problem:

I have this simple code to do something on a list of "TypeAs".. the variable "item" is getting type "Any" when it is very clear that the list is of type "TypeA[]". So, to have type safety and intellisense I have to cast the type.

    var list: TypeA[] = this.getListOfTypeAs();
    for (var item in list) {
        var typedItem = (<TypeA> item); //clearly a problem with typescript 

Why?

pabloelustondo
  • 2,196
  • 3
  • 19
  • 23

2 Answers2

10

As pointed out by Zev and stated in the documentation:

The for..in statement iterates over the enumerable properties of an object, in arbitrary order.

In TypeScript 1.5+ you can use for...of to iterate over the elements in an array:

var list: TypeA[] = this.getListOfTypeAs();
for (let item of list) {
    // item is an element of list in here
}

While in previous versions you can use a standard for loop:

var list: TypeA[] = this.getListOfTypeAs();
for (var i = 0; i < list.length; i++) {
    var typedItem = item[i];
}
Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
6

Because Javascript's for...in iterates over the property names of an object/array, not the values of the properties.

Community
  • 1
  • 1
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136