> ## 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.

# TypeScript Generator Method

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.

```typescript theme={"dark"}
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:

```typescript theme={"dark"}
type IteratorResult<T, TReturn = any> = 
    | { done: false, value: T }
    | { done: true, value: TReturn };
```

**Mechanics Visualization:**

```typescript theme={"dark"}
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.

```typescript theme={"dark"}
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>`.

```typescript theme={"dark"}
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.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
