function* createFibonacciGenerator(){
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
let fibonacciGenerator = createFibonacciGenerator(); // IterableIterator<number>
fibonacciGenerator.next(); // {value: 0, done: false}
fibonacciGenerator.next(); // {value: 1, done: false}
- The asterisk
*
before a function’s name makes that function a generator. Calling a generator returns an iterable iterator. - Generators use
yield
keyword to yield values. - Typescript is able to infer the type of our iterator from the type of value we yielded.
- Call
next()
on the iterator to get the next value.