Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 96 ยท Async and Errors

Iterators and Generators

Type iteration in TypeScript - Iterable<T>, Iterator<T>, IteratorResult, Generator<T, R, N>, yield*, async generators and the ES2025 iterator helpers.

for...of, spread syntax, Array.from, destructuring, new Map(entries) and Promise.all all work with one shared idea: the iteration protocol. An object is iterable if it has a [Symbol.iterator]() method that returns an iterator, and an iterator is anything with a next() method that hands out { value, done } results one at a time. Generators are the easy way to write iterators: a function with yield that pauses after each value.

The JavaScript side of this is covered in JavaScript iterators and generators. This lesson is about the types: Iterable<T> and Iterator<T>, the IteratorResult union that makes done meaningful, the three type parameters of Generator<T, TReturn, TNext>, async generators, and how TypeScript types the new iterator helper methods (map, filter, take and friends) that arrived with ES2025.

Iterable: the type for anything you can loop over

Iterable<T> describes any object you can use in for...of to get values of type T. Arrays, strings, Sets, Maps, typed arrays, generator objects and many Node APIs are all iterable. If a function only needs to loop over its input once, typing the parameter as Iterable<T> instead of T[] lets callers pass any of them:

TypeScript Accepting any iterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is 6, 30, 12, 300, juice and a. The last one is a reminder that a string iterates characters, so 'abc' is a valid Iterable<string>, and the longest "word" in it is just 'a'.

Use Iterable<T> when you loop once, and readonly T[] (or ArrayLike<T>) when you need .length, indexing or several passes. An iterable may be a one-shot stream, like a generator, that is empty the second time you loop over it.

Iterator and IteratorResult

Behind every for...of loop, the engine calls next() repeatedly. TypeScript types each result as IteratorResult<T, TReturn>, a discriminated union on done:

TypeScript
type IteratorResult<T, TReturn = any> =
  | { done?: false; value: T }          // IteratorYieldResult<T>
  | { done: true; value: TReturn };     // IteratorReturnResult<TReturn>

So value is T only after you check done. When you call next() by hand, TypeScript makes you do that check, which this example shows. It also implements an iterator object manually, so you can see every piece of the protocol:

TypeScript Calling next() by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Inside the loop, step.value is a number, so toFixed is allowed; after the loop, step.done is true and step.value is the string return value. Without the done check, first.value.toUpperCase() would fail with error TS18048: 'first.value' is possibly 'undefined'. That's the strictBuiltinIteratorReturn flag (part of strict since TypeScript 5.6): built-in iterators like ArrayIterator, SetIterator and MapIterator declare their finished value as undefined, so you can't forget that next() may report the end.

countdown returns an Iterator, not an Iterable: you can call next() on it but you can't put it in a for...of, because it has no [Symbol.iterator] method. Generators, below, give you both at once.

Making your own classes iterable

To make a class work with for...of and spread, give it a [Symbol.iterator]() method. The simplest implementation is a generator method, written with a * before the name. Adding implements Iterable<T> makes TypeScript check that the method returns the right kind of iterator:

TypeScript An iterable Range class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each for...of calls [Symbol.iterator]() again and gets a fresh generator, so a Range can be looped over as many times as you like. That's the difference between an iterable collection (reusable) and an iterator (consumed once).

The three Generator type parameters

A generator object has a three-part type:

Parameter Meaning In code
T the type of each yielded value yield value
TReturn the type of the final value, when done is true return value
TNext the type passed in through next(x) the result of a yield expression

TypeScript infers all three from the function body: function* ids() { yield 1; } is a () => Generator<number, void, unknown>. Annotate the return type when you want a clear contract, especially for TNext. A generator that receives values works like a small stateful worker, and its next() parameter is checked:

TypeScript All three Generator type parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows averages 10 and 15, then the third next finishes the generator: done: 3 values, total 90. The very first next() call only starts the generator, so the value passed to it is thrown away. Without the @ts-expect-error comment (see migrating JavaScript for how it works), worker.next('forty') is a type error, because TNext is number.

The last line prints [ 'a', 'b' ]. for...of, spread and Array.from stop as soon as done is true and ignore the return value. You only see TReturn when you call next() yourself or delegate with yield*, which returns it.

Generator<T> with one type argument means Generator<T, any, any>. That loose any is rarely a problem for TReturn, but prefer Generator<T, void, undefined> (or simply let TypeScript infer) when the generator neither returns a value nor receives one. Some codebases use IterableIterator<T> or IteratorObject<T> as return types; they describe the same object with fewer details.

Delegating with yield*

yield* other yields every value from another iterable as if the current generator had produced them, and the whole yield* expression evaluates to the other generator's return value. That makes recursive generators over trees short and fully typed:

TypeScript Recursive generators with yield*

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Because paths declares TReturn as number, the expression yield* paths(child, path) has type number, and adding it to visited type-checks. The output lists /home, /home/docs, /home/docs/install, /home/docs/api, /home/blog, then nodes visited: 5.

Iterator helpers (ES2025)

Arrays have had map and filter forever, but those methods build a whole new array at every step. ES2025 added iterator helpers: methods on iterators themselves that work lazily, pulling one value at a time through the whole chain. They're available in Node 22+ and current browsers, and TypeScript types them in the esnext library our editor uses (es2025 in a tsconfig lib).

Generators and built-in iterators like array.values(), map.keys() and set.entries() all have them:

TypeScript Lazy pipelines with iterator helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first pipeline runs over an infinite generator safely: take(5) stops pulling after five values, so the generator only ever produces the numbers 1 to 9. The same chain written with array methods would never finish, because you can't build an infinite array first. The output starts with [ 1, 9, 25, 49, 81 ].

The helper methods return IteratorObject<T, undefined, unknown>, TypeScript's type for "a built-in iterator with helpers". Note what has helpers and what doesn't:

  • Have them: generator objects, array.values()/keys()/entries(), Map and Set iterators, string iterators, matchAll() results, and anything wrapped with Iterator.from().
  • Don't have them: arrays themselves (use the array methods, or call .values() first), plain Iterable<T> parameters (an object with only [Symbol.iterator]), and hand-written iterator objects like countdown above. Wrap those with Iterator.from(...).

Available methods: map, filter, take, drop, flatMap (lazy, return new iterators) and reduce, toArray, forEach, some, every, find (consume the iterator and return a result). Iterator.concat() is the next addition (newer runtimes such as Node 26 already ship it, but Node 24 and TypeScript 7.0's library don't have it yet), and helpers for async iterators are still a proposal.

Async generators

An async function* combines both worlds: it can await inside its body and yield values over time. Its type is AsyncGenerator<T, TReturn, TNext>, it implements AsyncIterable<T>, and you consume it with for await...of. Node's readline interface is an AsyncIterable<string> too, which makes reading input line by line a short loop:

TypeScript Async generators over standard input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The input box holds five lines, one empty and one malformed, so the program prints three records and then best: ada, skipped 2 line(s). Because the generator's TReturn is number, result.value after the loop is the skip count. Calling next() manually is what makes that return value reachable; a for await loop would have hidden it, just like for...of does for sync generators.

The promises lesson shows another async generator that pages through a simulated API. When an async generator holds a resource, like a file handle or a database cursor, close it in a finally block: for await calls the generator's return() method when the loop exits early, and finally runs then. The next chapter's using declarations give you another way to guarantee that cleanup.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these can be passed to function sum(values: Iterable<number>)?

    Iterable of number accepts anything with a Symbol.iterator method that yields numbers, which includes arrays, Sets, Map value iterators, typed arrays and generator objects.
  2. 2. In const r = [1, 2].values().next();, what is the type of r.value before you check r.done?

    IteratorResult is a union. Built-in iterators return undefined when finished (strictBuiltinIteratorReturn), so value is number or undefined until done is checked.
  3. 3. For function* g(): Generator<string, number, boolean>, what does next() accept?

    The third type parameter, TNext, is the type you send in with next(x). The first is what is yielded and the second is the return value.
  4. 4. What does console.log([...withReturn()]) print if the generator yields "a" and "b" and then returns 99?

    Spread and for...of stop when done is true and ignore the return value. Only next() calls and yield* expose it.
  5. 5. Why does naturals().map((n) => n * 2).take(3).toArray() finish even though naturals() is infinite?

    Each helper pulls one value at a time from the previous step. Once take has three values it reports done, and nothing more is computed.

Summary

  • Iterable<T> is "anything for...of can loop over" (arrays, strings, Set, Map, generators). Accept it in parameters when you only loop once.
  • An Iterator<T, TReturn> has next(), which returns IteratorResult<T, TReturn>, a union you narrow with done. Built-in iterators finish with undefined (strictBuiltinIteratorReturn).
  • Make a class iterable with a generator method *[Symbol.iterator]() and implements Iterable<T>; each loop gets a fresh iterator.
  • Generator<T, TReturn, TNext>: yielded values, the final return value, and the values sent in with next(x). for...of and spread ignore TReturn; yield* returns it.
  • ES2025 iterator helpers (map, filter, take, drop, flatMap, reduce, toArray, some, every, find, forEach) are lazy and typed as IteratorObject<T, undefined, unknown>; use .values() or Iterator.from() to get them.
  • async function* produces an AsyncGenerator<T, TReturn, TNext>; consume AsyncIterable<T> with for await, and clean up resources in finally.

Next: Decorators