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.
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.
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
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);
}
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);
}
})();
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.