Monthly Archives: December 2016

Slickest Way to Have an Index Counter Variable in a for..of Loop in TypeScript

There is no index variable available in a for..of loop in TypeScript. You can either use Array.prototype.forEach or my custom generator function:

interface IndexEnumerator extends Array {
  0: T;
  1: number;
}

function* indexEnumerator(iterable: Iterable) {
  let index = 0;
  for (let item of iterable) {
    yield <IndexEnumerator>[item, index];
    index++;
  }
}

Usage example:

interface Person {
  name: string;
  age: number;
}

let people: Person[] = [
  { name: 'Patrick', age: 23 },
  { name: 'Trong', age: 22 },
  { name: 'Hansruedi', age: 57 }
];

for (const [person, index] of indexEnumerator(people)) {
  console.log(`${person.name} is ${person.age} years old.`);
}