I\'m trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem.
My code is:
I'm using latest TS and node (v2.6 and v8.9 respectively) and I can do:
let myMap = new Map<string, boolean>();
myMap.set("a", true);
for (let [k, v] of myMap) {
console.log(k + "=" + v);
}
This worked for me.
Object.keys(myMap).map( key => {
console.log("key: " + key);
console.log("value: " + myMap[key]);
});
Per the TypeScript 2.3 release notes on "New --downlevelIteration":
for..of statements
, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using--downlevelIteration
This is not enabled by default! Add "downlevelIteration": true
to your tsconfig.json
, or pass --downlevelIteration
flag to tsc
, to get full iterator support.
With this in place, you can write for (let keyval of myMap) {...}
and keyval
's type will be automatically inferred.
Why is this turned off by default? According to TypeScript contributor @aluanhaddad,
It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).
If you can target ES2015 ("target": "es2015"
in tsconfig.json
or tsc --target ES2015
) or later, enabling downlevelIteration
is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from
conversion or forEach
or some other workaround).
This worked for me. TypeScript Version: 2.8.3
for (const [key, value] of Object.entries(myMap)) {
console.log(key, value);
}
Just use Array.from()
method to convert it to an Array
:
myMap : Map<string, boolean>;
for(let key of Array.from( myMap.keys()) ) {
console.log(key);
}
for (let [key, value] of map) {
console.log(key, value);
}
for (let entry of Array.from(map.entries())) {
let key = entry[0];
let value = entry[1];
}