This project is read-only.

TS supports dictionaries but has no For Each loop?

Topics: Language Specification
Jan 27, 2014 at 11:37 AM
TS supports dictionaries:
var persons : { [id : string] : Person}
but I greatly miss a For Each loop that would return the typed instance of such dictionary, like:
for each (person : Person in persons) {
Jan 27, 2014 at 1:00 PM
Edited Jan 27, 2014 at 1:14 PM
TS doesn't really add any extensions to the language per se. When you say TS supports dictionaries, that's because JavaScript does -in the sense that all objects are naturally dictionaries.

ECMAScript 6 will introduce the for...of statement, which TS will also almost certainly support (because TS is a superset of JS). You can use for...of to iterate over iterable objects or custom types by defining a generator.

Here are a couple of workarounds
interface Person {
    name: string;

var persons : { [id : string] : Person } = {};
persons["a1"] = { name: "foie", age: 1};
persons["a2"] = { name: "gras", age: 2};

// ECMAScript 5
.map(item => persons[item])
.forEach(person => {

// Prior versions
for(var id in persons){
    var person = persons[id];
See also:
Jan 27, 2014 at 2:11 PM

surely one can use the for .. in lop and cast things manually, I can't wait for the TS 1.0.

What is the right name for this kind of iteration, "for .. of" or "for .. each" and what is the difference?