7

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 custom objects.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
BrianLegg
  • 1,658
  • 3
  • 21
  • 36

1 Answers1

14

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101