Table of contents
- 1. Terminology
- 2. Generator functions
- 3. Iterator objects
- 4. Iterable objects
- 5. Video Tutorial
- 6. Summary
A generator function returns a lazy iterator, which generates data only on demand. In the following tutorial, Benny will show you how to code your own generator functions in TypeScript. You will learn the differences between iterators and iterables and how to refactor your code to use generator functions.
- A generator function is a function, which returns a generator object.
- A generator object is an object, which has the properties of an iterator and an iterable.
- An iterator is an object which defines a function called
next, which returns an object with the properties
- An iterable is an object which defines a key called
Symbol.iterator, which returns a generator function.
A generator function is a function, which returns a generator object. Generator functions get defined with an asterisk next to the
function keyword. The return value of a generator function is of type
IterableIterator, because every generator object is iterable and follows the iterator protocol. Values get returned with the
yield keyword, which returns a value on demand when calling the
next function from a generator object. Each subsequent call to
next continues processing from where the
yield keyword paused.
Iterators are objects implementing the iterator protocol. In simplified terms, an iterator is an object with a
next method. This next method has to return new objects, each of which has the properties
value (of type
done (of type
An object is iterable, when it defines a default iterator for the key of
- The iterator symbol (
Symbol.iterator) is a factory of iterators
- Iterators are useful to generate (an infinite amount of) data
- Iterables can be run in loops or spreaded into arrays
yieldkeyword can be used to pause and resume a generator function
- Generator functions are a concept of ES6 and can be used in TypeScript
- The return type of a generator function in TypeScript is an iterable iterator