Model stepwise value generation
Typing custom lazy producers
TypeScript · Interface
Iterator describes a stateful producer whose next method yields values until completion. Its generic parameters separately model yielded values, the final return value, and inputs passed to next.
Iterator models a stepwise producer: next optionally receives a value and returns an IteratorResult containing either a yielded value or a completion value. Optional return and throw methods let an implementation handle early completion or exceptions.
interface Iterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
return?(value?: TReturn): IteratorResult<T, TReturn>;
throw?(e?: any): IteratorResult<T, TReturn>;
}| Name | Type | Description |
|---|---|---|
T | unknown | Type produced while iteration continues. |
TReturn | unknown | Type produced when iteration completes. |
TNext | unknown | Type accepted by next when advancing the iterator. |
next, return, and throw return IteratorResult<T, TReturn>.
function drain<T>(iterator: Iterator<T>): T[] {
const values: T[] = [];
for (let result = iterator.next(); !result.done; result = iterator.next()) {
values.push(result.value);
}
return values;
}
const values = drain(["a", "b", "c"][Symbol.iterator]());
console.log(values);Consumes an iterator by repeatedly calling next() and collecting values until the result is marked done.
Typing custom lazy producers
Typing generator functions
Manual iteration
Protocol-compatible APIs
IterableIterableIteratorIteratorResultIteratorYieldResultIteratorReturnResultGenerator