Reputation: 2216
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?
Upvotes: 4
Views: 17512
Reputation: 106650
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];
}
Upvotes: 11
Reputation: 15327
Because Javascript's for...in
iterates over the property names of an object/array, not the values of the properties.
Upvotes: 7