BrianLegg BrianLegg - 1 year ago 85
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download