← Back to TypeScript Course | Chapter 21: Symbols and Iterators | Lesson 6 of 6

for...of with Types

The for...of loop iterates over iterable values such as arrays, strings, sets, maps, and generators. TypeScript uses the iterable's element type to infer the loop variable.

Iterating Typed Arrays

When iterating an array with for...of, TypeScript infers the loop variable's type directly from the array's element type, so iterating a string[] gives you a properly typed string on every pass.

Example: Iterating Typed Arrays

typescript
const names: string[] = ["Ravi", "Priya"];
for (const name of names) {
  console.log(name.toUpperCase());
}

Iterating Objects with Iterable Types

Plain objects aren't iterable with for...of unless they explicitly implement the iterable protocol — arrays, strings, and the built-in collection types all qualify automatically, but a bare {} literal never does.

Example: Iterating Objects with Iterable Types

typescript
const arr = [1, 2, 3];
for (const n of arr) console.log(n);
// A bare {} literal is not iterable and would fail here.

for...of with Sets

Set<T> is iterable and yields values of type T on each pass, so TypeScript preserves whatever element type the Set was declared with all the way through the loop.

Example: for...of with Sets

typescript
const ids: Set<number> = new Set([1, 2, 3]);
for (const id of ids) {
  console.log(id);
}

for...of with Maps

Map<K, V> is iterable over its entries as [key, value] pairs, so each loop variable in a for...of over a Map is inferred as a two-element tuple containing K and V.

Example: for...of with Maps

typescript
const scores: Map<string, number> = new Map([["Ravi", 90], ["Priya", 85]]);
for (const [name, score] of scores) {
  console.log(name, score);
}

for...of with Generators

Generators produce iterable sequences too, so the type a generator yields becomes the inferred type of the for...of loop variable when you iterate directly over a generator's results.

Example: for...of with Generators

typescript
function* letters(): Generator<string> {
  yield "a";
  yield "b";
}
for (const letter of letters()) {
  console.log(letter);
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.