Start Coding

Topics

TypeScript Generators

Generators in TypeScript provide a powerful way to create iterators with a more concise and readable syntax. They allow you to pause and resume function execution, making them ideal for handling asynchronous operations and creating infinite sequences.

Basic Syntax

To define a generator function in TypeScript, use the function* syntax. Here's a simple example:


function* countToThree() {
    yield 1;
    yield 2;
    yield 3;
}

const generator = countToThree();
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
console.log(generator.next().value); // 3
    

The yield keyword is used to pause the function and return a value. Each call to next() resumes the function until the next yield statement.

Infinite Sequences

Generators excel at creating infinite sequences without consuming excessive memory. Here's an example of an infinite counter:


function* infiniteCounter() {
    let i = 0;
    while (true) {
        yield i++;
    }
}

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

Using Generators with For...of Loops

Generators work seamlessly with for...of loops, making iteration simple and intuitive:


function* fibonacci() {
    let [prev, curr] = [0, 1];
    while (true) {
        yield curr;
        [prev, curr] = [curr, prev + curr];
    }
}

for (const num of fibonacci()) {
    if (num > 100) break;
    console.log(num);
}
    

Async Generators

TypeScript also supports async generators, which are particularly useful for handling asynchronous operations:


async function* fetchUserData(ids: number[]) {
    for (const id of ids) {
        const response = await fetch(`https://api.example.com/users/${id}`);
        yield await response.json();
    }
}

(async () => {
    for await (const user of fetchUserData([1, 2, 3])) {
        console.log(user);
    }
})();
    

Best Practices

  • Use generators for lazy evaluation of large or infinite sequences.
  • Combine generators with Async/Await in TypeScript for efficient asynchronous operations.
  • Leverage TypeScript's type system to ensure type safety when working with generators.
  • Consider using generators for implementing custom iterables in your classes.

Related Concepts

To deepen your understanding of TypeScript generators, explore these related topics:

Generators in TypeScript offer a powerful tool for managing complex iterations and asynchronous flows. By mastering their use, you can write more efficient and readable code, especially when dealing with large data sets or time-consuming operations.