10

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.

2
  • Why you use for..in with array? use .map instead. Commented Aug 15, 2016 at 15:41
  • while this may be a duplicate question, the answer provided by Bruno is unique and is exactly what I needed. Commented Aug 15, 2016 at 15:49

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for. Thank you. I will accept your answer when the timer lets me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.