TypeScript Iterators & Generators
A for...of loop works on arrays, strings, Maps, Sets — and on any object you build yourself, as long as it follows the iteration protocol. TypeScript describes that protocol with a handful of built-in interfaces, so your custom collections and generator functions are fully type-checked.
The iteration protocol
An object is iterable when it has a method under the key Symbol.iterator that returns an iterator. An iterator has a next() method that returns { value, done } results.
| Interface | What it describes |
|---|---|
Iterable<T> |
has [Symbol.iterator](): Iterator<T> |
Iterator<T> |
has next(): IteratorResult<T> |
IteratorResult<T> |
{ done: false, value: T } or { done: true, value: ... } |
IterableIterator<T> |
an iterator that is also iterable (what generators and .entries() return) |
Generator<T, TReturn, TNext> |
the object a generator function returns |
Here is a hand-written iterable range. Because it implements Iterable<number>, for...of and the spread operator both work, and the loop variable is typed as number:
class NumberRange implements Iterable<number> {
constructor(private start: number, private end: number, private step = 1) {}
[Symbol.iterator](): Iterator<number> {
let current = this.start;
const { end, step } = this;
return {
next(): IteratorResult<number> {
if (current > end) return { done: true, value: undefined };
const value = current;
current += step;
return { done: false, value };
},
};
}
}
for (const n of new NumberRange(1, 5)) {
console.log(n * n);
}
console.log([...new NumberRange(0, 20, 5)]);1
4
9
16
25
[ 0, 5, 10, 15, 20 ]
If you forget part of the protocol, the compiler tells you exactly what is missing:
const letters = {
items: ["a", "b"],
};
for (const ch of letters) {
console.log(ch);
}main.ts(5,18): error TS2488: Type '{ items: string[]; }' must have a '[Symbol.iterator]()' method that returns an iterator.
Generator functions
Writing next() by hand is tedious. A generator function (function*) does the bookkeeping for you: each yield hands one value to the consumer and pauses the function until the next value is requested. TypeScript infers the return type as Generator<...>:
function* countdown(from: number) {
while (from > 0) {
yield from;
from--;
}
return "liftoff";
}
const gen = countdown(3);
console.log(gen.next());
console.log([...gen]); // the rest of the values
console.log(gen.next());{ value: 3, done: false }
[ 2, 1 ]
{ value: undefined, done: true }
Notice that the spread operator collects only yielded values; the return value "liftoff" is delivered once, by the next() call that finishes the generator (here consumed internally by the spread).
The three type parameters of Generator<T, TReturn, TNext> are the yielded type, the returned type and the type that next(value) sends into the generator. You can write them explicitly:
function* runningTotal(): Generator<number, void, number> {
let total = 0;
while (true) {
const added = yield total; // `added` is typed as number
total += added;
}
}
const acc = runningTotal();
acc.next(); // start the generator
console.log(acc.next(5).value);
console.log(acc.next(10).value);
console.log(acc.next(2.5).value);5
15
17.5
Making classes iterable with generators
The neatest way to implement [Symbol.iterator] is a generator method, written *[Symbol.iterator]():
class Playlist implements Iterable<string> {
private songs: string[] = [];
add(...titles: string[]) {
this.songs.push(...titles);
return this;
}
*[Symbol.iterator]() {
for (const [i, title] of this.songs.entries()) {
yield `${i + 1}. ${title}`;
}
}
}
const list = new Playlist().add("Intro", "Blue Sky", "Outro");
for (const line of list) console.log(line);1. Intro
2. Blue Sky
3. Outro
Lazy pipelines
Generators produce values only on demand, so they can even describe infinite sequences. Small helper generators with generic types compose into lazy pipelines:
function* naturals() {
let n = 1;
while (true) yield n++;
}
function* filter<T>(src: Iterable<T>, keep: (x: T) => boolean) {
for (const x of src) if (keep(x)) yield x;
}
function* take<T>(src: Iterable<T>, count: number) {
if (count <= 0) return;
for (const x of src) {
yield x;
if (--count === 0) return;
}
}
const evens = filter(naturals(), (n) => n % 2 === 0);
console.log([...take(evens, 5)]);[ 2, 4, 6, 8, 10 ]
Tip: Type helper parameters as
Iterable<T>rather thanT[]. Then they accept arrays, sets, maps, strings and generators alike.
Note: There are async versions too:
async function*yields promises and is consumed withfor await...of; its type isAsyncGenerator<T>.
Test yourself
What must an object have to be used in a for...of loop?
- A
lengthproperty - A
[Symbol.iterator]()method - A
forEachmethod - An index signature
In Generator<string, number, boolean>, what is number?
- The yielded type
- The type passed to
next() - The return type
- The index type
Why can a generator describe an infinite sequence safely?
- TypeScript limits it to 1000 items
- Values are produced lazily, only when requested
- It runs in a separate thread
- It caches all values