Typescript type inference inside for loop

15.1k views Asked by At

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?

2

There are 2 answers

2
Zev Spitz On

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

0
David Sherret On

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];
}