CodingIntrigue
CodingIntrigue

Reputation: 78555

Using for..of with Map generates invalid ES5

I'm having an issue using the latest TypeScript 1.5 compiler in conjunction with Map and for..of. Example:

var map: Map<string, string> = new Map<string, string>();
map.set("A", "one");
map.set("B", "two");
map.set("C", "three");
for(let [key, value] of map) {
    console.log(key, value);
}

According to this, TypeScript 1.5 supports destructuring and for..of so I can't really see why this shouldn't work, but it outputs invalid ES5:

for (var _i = 0, _a = map; _i < _a.length; _i++) {
//                              ^^^^^^^^^
// A Map doesn't have a length, so this block never executes
    var _b = _a[_i], key = _b[0], value = _b[1];
    console.log(key, value);
}

I worked around this by using map.forEach((value, key) => { ... }); but it's not as nice as for..of.

Is this a limitation of the 1.5 release? Am I expecting it to transpile Map to ES5 when it's not supported?

Upvotes: 1

Views: 297

Answers (1)

Paleo
Paleo

Reputation: 23712

The syntax for of that is supported by TypeScript with targets ES3/5, is very limited. Iterables need the target ES6.

Is this a limitation of the 1.5 release?

Yes:

This works for arrays and strings. Other iterables will not be supported for ES3/ES5 (Source)

Upvotes: 1

Related Questions