Iterables, generators and async iterators
Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.
What you will be able to do
#- Type Iterable, Iterator and Generator.
- Write a typed generator function.
- Consume an async iterable with for await.
Overview
#Iterable protocol
function toArray<T>(iterable: Iterable<T>): T[] {
return [...iterable];
}
Iterable<T> requires a [Symbol.iterator] method. Array, Set, Map and strings all satisfy it.
Generators
function* range(start: number, end: number): Generator<number, void, unknown> {
for (let i = start; i < end; i++) yield i;
}
The three type arguments are the yield type, the return type and the type passed to next.
Typed for-of
for (const value of range(0, 3)) {
console.log(value); // number
}
Async iterables
async function* stream(urls: string[]): AsyncGenerator<string, void, unknown> {
for (const url of urls) yield await fetch(url).then((r) => r.text());
}
for await (const chunk of stream(urls)) {
console.log(chunk.length);
}
for await works on any AsyncIterable<T>.
Downlevel iteration
With a target below ES2015, for-of over a non-array needs downlevelIteration. Prefer a modern target.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement `function* take<T>(iterable: Iterable<T>, n: number): Generator<T>` yielding at most n items.
starter.typescriptexport function* take<T>(iterable: Iterable<T>, n: number): Generator<T> { // your code }Reveal the reference answer
reference.typescriptexport function* take<T>(iterable: Iterable<T>, n: number): Generator<T> { let count = 0; for (const value of iterable) { if (count >= n) return; yield value; count += 1; } }Authored expected output: Compiles with no errors. Runtime: [...take([1, 2, 3, 4], 2)] is [1, 2].
The generator yields lazily and returns early once n items are produced.
Exercise 2Predict
What is the type of `value`? ```ts for (const value of new Set([1, 2])) {} ```
Exercise 3Explain
What do the three type arguments of `Generator<Y, R, N>` mean?
Reveal the reference answer
reference.typescriptThe first argument is the type yielded by yield. The second is the type returned when the generator finishes, which is the value of the return statement. The third is the type accepted by next, which flows back into the generator as the result of a yield expression. Most generators use void or unknown for the third argument.Authored expected output: A written answer naming yield, return and next-argument types.
The three parameters describe the three ways data crosses the generator boundary.
Common misconceptions
#- A generator returns an array.
- for await only works on promises.
- Iterable and Iterator are the same type.
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.