BrianLegg BrianLegg - 10 months ago 49
Javascript Question

For-in loop in Typescript always treats variable like a string

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.


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