Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-in loop in Typescript always treats variable like a string [duplicate]

This is something that has been bugging me for a while now. In Typescript if I define a For-in loop my variable is always treated as a string. Example:

for(var room in this.rooms) {
    room.placement.x = 52;
}

The "room.placement.x" will fail because it treats "room" as a string. "this.rooms" is actually a collection of Room objects, but room is not a Room... it's a string.

Is this a Typescript version issue or something that is sticking around. It's highly frustrating.

Is there a way to define room so that Typescript can treat it like a Room?

The definition of rooms is: "private rooms: Room.Game.Room[];"

It's an array of a custom object.

like image 917
BrianLegg Avatar asked Aug 15 '16 15:08

BrianLegg


People also ask

What is for of loop in TypeScript?

The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object.

How do I loop through a string in TypeScript?

To iterate over a string with index: Use the spread syntax (...) to unpack the string into an array. Use the forEach() method to iterate over the array. The second parameter the forEach() method takes is the index of the current element.

Should you use for in loop?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

How for in loop works in JavaScript?

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. When a for loop executes, the following occurs: The initializing expression initialExpression , if any, is executed.


1 Answers

If this.rooms is an array, the proper syntax is for ...of

for (let room of this.rooms) {
    room.placement.x = 52;
}

for ... in iterates over the keys

see this for more

like image 107
Bruno Grieder Avatar answered Oct 21 '22 03:10

Bruno Grieder