Skip to main content
A generator method is a specialized function defined within a class or object literal, denoted by an asterisk (*), that returns a Generator or IterableIterator object. Unlike standard methods that execute to completion in a single synchronous frame, generator methods act as state machines. They can pause execution using the yield keyword and resume execution when the consumer invokes the next() method on the returned generator instance.

TypeScript Typing for Generators

In TypeScript, generator methods are strictly typed using the built-in Generator<T, TReturn, TNext> generic interface.
  • T (Yield Type): The type of the values emitted by the yield expressions.
  • TReturn (Return Type): The type of the final value returned by the generator when it completes (via a return statement or implicitly returning undefined).
  • TNext (Next Type): The type of the value injected back into the generator when passing an argument to iterator.next(value).

Syntax and Declaration

Generator methods can be declared inside classes or object literals. The asterisk is placed immediately before the method name.

Execution Mechanics and IteratorResult

Invoking a generator method does not execute its body. Instead, it instantiates and returns the generator object. Execution only begins when next() is called. Each call to next() returns an IteratorResult<T, TReturn> object, which conforms to the following interface:
Mechanics Visualization:

Delegation with yield*

Generator methods can delegate control to another iterable or generator method using the yield* expression. TypeScript enforces that the yielded types of the delegated iterable are compatible with the T type of the parent generator method.

Asynchronous Generator Methods

If a generator method needs to await promises before yielding, it must be declared as an async generator method using async *. The return type changes from Generator to AsyncGenerator<T, TReturn, TNext>.
In this asynchronous context, the next() method returns a Promise<IteratorResult<T, TReturn>>, requiring the consumer to await the result of each iteration.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More