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?

0

2 Answers 2

11

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

Comments

7

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

2 Comments

Thanks. I see. So, if I understood, still using "in", my code can be fixed using: for (var i in list) { var typedItem = list[i];
@pabloelustondo it's not recommended. Read this.

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.