Skip to main content
A generator function is a special class of function that can pause its execution context and yield multiple values over time, rather than computing and returning a single value synchronously. When invoked, it does not execute its body immediately; instead, it returns a Generator object that conforms to both the Iterable and Iterator protocols.

Syntax and Declaration

Generators are declared using the function* syntax. Inside the function body, the yield keyword is used to emit a value and suspend the function’s execution state.

TypeScript Typing

In TypeScript, the return type of a generator function is explicitly defined using the generic Generator<T, TReturn, TNext> interface.
  • T (Yield Type): The type of values emitted by the yield statements.
  • TReturn (Return Type): The type of the final value returned by the function when it completes (via the return statement). Defaults to void or any if omitted.
  • TNext (Next Type): The type of the value accepted by the next() method, which is injected back into the generator at the point of the suspended yield. Defaults to unknown.

Execution Mechanics

Interacting with a generator involves calling the next() method on the instantiated Generator object. Each call to next() returns an IteratorResult object containing two properties:
  • value: The yielded or returned value.
  • done: A boolean indicating whether the generator has completed its execution.

Delegation with yield*

A generator can delegate its yielding behavior to another generator or iterable object using the yield* expression. TypeScript infers the yielded types of the delegated iterable and merges them into the parent generator’s type signature.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More