for...of with Types
In this page:
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
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
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
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
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
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: