TypeScript Iterators and Generators
Iterators and generators are important patterns for working with collections in JavaScript/TypeScript.
They provide a unified way to traverse data, making it simpler to handle large data streams, infinite sequences, and more.
Why Iterators and Generators Are Needed
When working with collection data, we often need to traverse data structures such as arrays and objects.
Iterators provide a unified, customizable traversal interface that allows any object to be traversed.
Generators are a concise way to create iterators; they let you use functions to pause and resume execution, making them ideal for handling large data streams or infinite sequences.
Concept explanation:An iterator is an object that provides a next() method for traversing data. A generator is a special function that can pause during execution and return a value.
Iterable protocol
Objects that implement the Symbol.iterator method can be traversed by a for...of loop.
Example
// Arrays are iterable by default
var
arr
=
[
1
,
2
,
3
]
;
for
(
var
_i
=
0
,
arr_1
=
arr
;
_i
<
arr_1.
length
;
_i
++
)
{
var
item
=
arr_1
[
_i
]
;
console.
log
(
"Array elements: "
item
)
;
}
// Strings are iterable by default
var
str
=
"hello"
;
for
(
var
_i
=
0
,
str_1
=
str
;
_i
<
str_1.
length
;
_i
++
)
{
var
char
=
str_1
[
_i
]
;
console.
log
(
"Character: "
char
)
;
}
Running result:
数组元素: 1
数组元素: 2
数组元素: 3
字符: h
字符: e
字符: l
字符: l
字符: o
Explanation:Arrays and strings both implement the Symbol.iterator method internally, so they can be traversed directly with for...of.
Custom iterable objects
Make a plain object implement the Symbol.iterator interface so it can be traversed.
Example
// Create a custom iterable object: range
var
range
=
{
from
:
1
,
to
:
5
,
// Implement the Symbol.iterator method
[
Symbol.
iterator
]
:
function
(
)
{
return
{
current
:
this
.
from
,
last
:
this
.
to
,
// The next method returns the iteration result
next
:
function
(
)
{
if
(
this
.
current
<=
this
.
last
)
{
// Not done, return the current value and increment
return
{
done
:
false
,
value
:
this
.
current
++
}
;
}
// Done
return
{
done
:
true
,
value
:
undefined
}
;
}
}
;
}
}
;
// Traverse with for...of
for
(
var
_i
=
0
,
range_1
=
range
;
_i
<
range_1.
length
;
_i
++
)
{
var
num
=
range_1
[
_i
]
;
console.
log
(
"Range: "
num
)
;
}
Iterator protocol:An iterator must have a next() method that returns an object in the form { done: boolean, value: any }.
Generator functions
Use the function* syntax to create a generator, and use yield to pause execution and return a value.
Example
// Generator function: using function* syntax
function
numberGenerator
(
)
{
yield
1
;
// Pause and return 1
yield
2
;
// Pause and return 2
yield
3
;
// Pause and return 3
}
// Create a generator instance
var
gen
=
numberGenerator
(
)
;
// Each call to next() executes up to the next yield
console.
log
(
"First: "
gen.
next
(
)
.
value
)
;
console.
log
(
"Second: "
gen.
next
(
)
.
value
)
;
console.
log
(
"Third: "
gen.
next
(
)
.
value
)
;
console.
log
(
"Completed: "
gen.
next
(
)
.
done
)
;
Running result:
第一个: 1
第二个: 2
第三个: 3
完成: true
Generator:A generator function returns an iterator, and each call to next() executes up to the next yield statement.
Infinite generators
Generators can produce infinite sequences; thanks to lazy evaluation, they do not consume infinite memory.
Example
// Infinite number generator
// Each call generates only one number, rather than generating all numbers at once
function
infiniteNumbers
(
)
{
var
n
=
1
;
while
(
true
)
{
// infinite loop
yield n
++;
// Pause and return the current value, then increment
}
}
var
gen
=
infiniteNumbers
(
)
;
console.
log
(
"1st: "
gen.
next
(
)
.
value
)
;
console.
log
(
"2nd: "
gen.
next
(
)
.
value
)
;
console.
log
(
"3rd: "
gen.
next
(
)
.
value
)
;
// Only get the first 5 numbers
var
nums
=
[
]
;
var
iter
=
infiniteNumbers
(
)
;
for
(
var
i
=
0
;
i
<
5
;
i
++
)
{
nums.
push
(
iter.
next
(
)
.
value
)
;
}
console.
log
(
"First 5: "
nums
)
;
Running result:
第1个: 1
第2个: 2
第3个: 3
前5个: 1,2,3,4,5
Lazy evaluation:The greatest advantage of generators is lazy evaluation: the next value is only computed when next() is called, making them ideal for handling infinite sequences.
Delegating generators
Use yield* to delegate to another generator or iterable object.
Example
// The first generator
function
gen1
(
)
{
yield
1
;
yield
2
;
}
// The second generator
function
gen2
(
)
{
yield
3
;
yield
4
;
}
// Combined generator: using yield* delegation
function
combined
(
)
{
yield
gen1
(
)
;
// Delegate to gen1
yield
gen2
(
)
;
// Delegate to gen2
}
// Traverse the combined generator
for
(
var
_i
=
0
,
combined_1
=
combined
(
)
;
_i
<
combined_1.
length
;
_i
++
)
{
var
num
=
combined_1
[
_i
]
;
console.
log
(
"Value: "
num
)
;
}
Running result:
值: 1
值: 2
值: 3
值: 4
yield*:Delegating generators can combine multiple generators or iterable objects, making them ideal for building reusable data streams.
TypeScript Generator Types
Generator type annotations use the Generator type.
Example
// Generator type: Generator
function
idGenerator
(
)
:
Generator
<
number
,
void
,
unknown
{
var
i
=
1;
while
(
i
<=
3
)
{
yield i
++;
// yield number type
}
// return void
}
var
gen
=
idGenerator
(
)
;
console.
log
(
Array
.
from
(
gen
)
)
;
Type explanation:Generator
It means: T is the type yielded, R is the final return type, and N is the type of the next() parameter.
Notes
- **Iterator protocol:** implement Symbol.iterator to return an object with a next() method
- **Generator syntax:*use function rather than function
- **yield keyword:** pause execution and return a value
- **Lazy evaluation:** generators compute on demand and do not generate all values at once
**Best practice:** use generators when handling large data streams, infinite sequences, or scenarios that require pausing/resuming.
Summary
Iterators and generators are powerful data-processing tools in TypeScript.
- **Iterable objects:** implement the Symbol.iterator interface
- **Generator:*use function and yield to create
- **yield:** pause execution and return a value
- **Delegation:*use yield combine multiple generators
Note:Use iterators and generators when you need to traverse custom objects, process data streams, or create infinite sequences.