Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
class DataStream {
    // T = number, TReturn = string, TNext = boolean
    *processStream(): Generator<number, string, boolean> {
        // Execution pauses here, yielding 1. 
        // The boolean passed to the next() call is assigned to 'condition'.
        const condition: boolean = yield 1; 
        
        if (condition) {
            yield 2;
        }
        
        return "Stream Complete";
    }
}

const literalGenerator = {
    *generateKeys(): Generator<string, void, unknown> {
        yield "key_1";
        yield "key_2";
    }
};

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:
type IteratorResult<T, TReturn = any> = 
    | { done: false, value: T }
    | { done: true, value: TReturn };
Mechanics Visualization:
const stream = new DataStream();
const iterator = stream.processStream(); // Method body has not executed yet

// Starts execution, runs to the first yield.
const step1 = iterator.next(); 
// step1: { value: 1, done: false }

// Resumes execution, injects 'true' into the 'condition' variable.
const step2 = iterator.next(true); 
// step2: { value: 2, done: false }

// Resumes execution, hits the return statement.
const step3 = iterator.next(false); 
// step3: { value: "Stream Complete", done: true }

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.
class TreeTraversal {
    *leftBranch(): Generator<number, void, unknown> {
        yield 1;
        yield 2;
    }

    *traverse(): Generator<number, void, unknown> {
        yield 0;
        // Delegates execution to leftBranch() until it completes
        yield* this.leftBranch(); 
        yield 3;
    }
}

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>.
class AsyncDataFetcher {
    async *fetchChunks(): AsyncGenerator<Uint8Array, void, unknown> {
        const chunk1 = await Promise.resolve(new Uint8Array([1, 2]));
        yield chunk1;
        
        const chunk2 = await Promise.resolve(new Uint8Array([3, 4]));
        yield chunk2;
    }
}
In this asynchronous context, the next() method returns a Promise<IteratorResult<T, TReturn>>, requiring the consumer to await the result of each iteration.
Master TypeScript with Deep Grasping Methodology!Learn More