Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

TypeScript · Interface

Iterator

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.

Since
TypeScript 3.6

How it works

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.

Syntax

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>;
}

Parameters

NameTypeDescription
TunknownType produced while iteration continues.
TReturnunknownType produced when iteration completes.
TNextunknownType accepted by next when advancing the iterator.

Returns

next, return, and throw return IteratorResult<T, TReturn>.

Key points

  • An iterable creates an iterator through Symbol.iterator, while an iterator advances through values with next().
  • Use Iterator<T, TReturn, TNext> to model yielded values, the completion value, and values supplied to next.
  • next accepts either no argument or one value of TNext and produces an IteratorResult.
  • return is optional and can complete iteration with a value of TReturn.
  • throw is optional and allows an error to be injected into the iterator.
  • IteratorResult distinguishes yielded and completed results using the done property.

Common mistakes

  • Iterator has separate generic parameters for yielded values, the final returned value, and the input accepted by next; do not assume they are identical.
  • Always inspect done before treating value as a yielded T, because the final result may represent the iterator's return value.

Example: Consume an iterator

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.

When to use it

Model stepwise value generation

Typing custom lazy producers

Describe yield, return, and next types

Typing generator functions

Consume values with next()

Manual iteration

Accept iterator implementations

Protocol-compatible APIs

  • Iterable
  • IterableIterator
  • IteratorResult
  • IteratorYieldResult
  • IteratorReturnResult
  • Generator

Source: Documentation - TypeScript 3.6. Checked 2026-10-15.