πŸ”„ TypeScript – Iterators and Generators: A Complete Guide with Practical Examples

🧲 Introduction – What Are Iterators and Generators in TypeScript?

Iterators and Generators in TypeScript are advanced features that help you handle sequences of data in a lazy and memory-efficient manner. They allow you to define custom iteration behavior, making it easier to work with large or infinite datasets, implement coroutines, or create streaming APIs.

In JavaScript (and thus TypeScript), these constructs are built on the iterator protocol and generator functions, providing powerful tools for building loops that remember state across executions.

🎯 In this article, you’ll learn:

  • What iterators are and how they work
  • How to implement the iterable and iterator protocols
  • How generator functions simplify iteration
  • Use cases for iterators and generators in TypeScript

πŸ“˜ What Are Iterators in TypeScript?

An iterator is an object that conforms to the iterator protocol β€” it must have a next() method that returns an object with two properties:

{ value: T, done: boolean }

βœ… Basic Iterator Example:

function createIterator(): Iterator<number> {
  let count = 0;
  return {
    next(): IteratorResult<number> {
      if (count < 3) {
        return { value: count++, done: false };
      } else {
        return { value: undefined, done: true };
      }
    }
  };
}

const iterator = createIterator();
console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

πŸ” What Is an Iterable?

An iterable is an object that implements the Symbol.iterator method, which returns an iterator. Iterables can be used in for...of loops and spread operations.

βœ… Custom Iterable Example:

const range = {
  start: 1,
  end: 4,
  [Symbol.iterator](): Iterator<number> {
    let current = this.start;
    const end = this.end;
    return {
      next(): IteratorResult<number> {
        return current <= end
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      }
    };
  }
};

for (const num of range) {
  console.log(num); // 1, 2, 3, 4
}

πŸ“Œ Any object with a [Symbol.iterator]() method is considered iterable.


βš™οΈ Iterator Interfaces in TypeScript

TypeScript includes built-in types to describe iterables and iterators:

interface Iterator<T> {
  next(): IteratorResult<T>;
}

interface Iterable<T> {
  [Symbol.iterator](): Iterator<T>;
}

interface IteratorResult<T> {
  value: T;
  done: boolean;
}

You can use these interfaces to strongly type your custom implementations.


⚑ What Are Generators in TypeScript?

A generator is a special function that can pause and resume execution using the yield keyword. Generator functions are defined using the function* syntax.

βœ… Generator Syntax:

function* numberGenerator(): Generator<number> {
  yield 10;
  yield 20;
  yield 30;
}

const gen = numberGenerator();

console.log(gen.next()); // { value: 10, done: false }
console.log(gen.next()); // { value: 20, done: false }
console.log(gen.next()); // { value: 30, done: false }
console.log(gen.next()); // { value: undefined, done: true }

πŸ“Œ Each call to .next() resumes the generator from where it left off.


πŸ”„ Using for...of with Generators

Generators are iterable by nature, so they work seamlessly with for...of:

for (const num of numberGenerator()) {
  console.log(num);
}

Output:

10
20
30

πŸ”„ Generator Parameters and return

You can pass values into a generator and receive a final result with return.

function* greet(): Generator<string, string, unknown> {
  const name = yield "What's your name?";
  return `Hello, ${name}`;
}

const greeter = greet();
console.log(greeter.next()); // { value: "What's your name?", done: false }
console.log(greeter.next("Alice")); // { value: "Hello, Alice", done: true }

πŸ” Signature Breakdown:

Generator<YieldType, ReturnType, NextParamType>

πŸ“š Real-World Use Cases for Iterators and Generators

Use CaseBenefit
Custom iteration logicControl exactly how and when items yield
Lazy data processingProcess large/infinite data without memory issues
Coroutine simulationsPause/resume function logic
Streaming APIsEfficiently process data chunks
UI animation/state flowsModel step-by-step operations

🧠 Generator vs Iterator – What’s the Difference?

FeatureIteratorGenerator
SyntaxManual object with .next()function* with yield
Ease of UseMore verboseCleaner and automatic
IterabilityMust implement [Symbol.iterator]()Already iterable
Return ValueManual controlSupports yield and return

🧩 Advanced Tip: Infinite Generator

function* infiniteCounter(): Generator<number> {
  let count = 0;
  while (true) {
    yield count++;
  }
}

const counter = infiniteCounter();

console.log(counter.next().value); // 0
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2

⚠️ Useful for pagination, event queues, or simulation systems.


βœ… Summary – TypeScript Iterators and Generators

Iterators and generators in TypeScript empower developers to implement custom iteration logic, lazy data processing, and step-by-step control over execution flow. With strong type safety and built-in protocol support, they offer clean, efficient ways to manage sequences.

πŸ” Key Takeaways:

  • Iterators follow the .next() pattern and return { value, done }
  • Iterables must implement [Symbol.iterator]()
  • Generators simplify iteration with function* and yield
  • Strong typing with Iterator, Iterable, and Generator interfaces
  • Ideal for memory-efficient data handling and reactive workflows

βš™οΈ Real-world relevance:

Generators and iterators are used in:

  • UI component rendering (step-by-step)
  • Data stream handling
  • Infinite scrolling and pagination
  • Simulation/game loop control
  • Dynamic workflows (e.g., form wizards)

❓ FAQs – TypeScript Iterators and Generators

❓ What is the difference between an iterator and iterable?

  • An iterator is the object returned by the iterable’s [Symbol.iterator]() method.
  • An iterable is any object that implements [Symbol.iterator]().

❓ Are generator functions automatically iterable?

βœ… Yes. Generators implement both the iterator and iterable interfaces, so they can be used directly in for...of loops.


❓ Can I type a generator in TypeScript?

βœ… Use the Generator<YieldType, ReturnType, NextType> generic to type a generator function.


❓ When should I use a generator instead of an array?

Use a generator when:

  • You want to produce values lazily
  • You’re working with infinite or large sequences
  • You need to pause/resume function execution

❓ Can a generator return a final value?

βœ… Yes. The return value is accessible via .next().value when done === true.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TypeScript – Iterators and Generators

Or Copy Link

CONTENTS
Scroll to Top