I am trying to use generator function in typescript. But the compiler throws error
error TS2339: Property 'next' does not exist on type
Below is an closest sample of my code.
export default class GeneratorClass { constructor() { this.generator(10); this.generator.next(); } *generator(count:number): Iterable<number | undefined> { while(true) yield count++; } }
Here is the playground link for the same
The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function* syntax. When called, generator functions do not initially execute their code.
Generators create electrical energy to power appliances running on electricity by burning the fuel it uses for producing electricity. The generator includes different elements like a fuel system, engine, voltage regulator, alternator, a control panel, lubrication system, cooling, and exhaust system.
Generator functions are defined using the * asterisk either immediately after the function keyword or right before the function name. The below example creates an infinite number of natural numbers, which can be used when needed. We can use the yield* to call another generator from within a generator.
The next
method exists on the generator that the function returns, not on the generator function itself.
export default class GeneratorClass { constructor() { const iterator = this.generator(10); iterator.next(); } *generator(count:number): IterableIterator<number> { while(true) yield count++; } }
I was seeing this error because my tsconfig.json was targeting es5
.
I simply changed (excerpted) from:
"target": "es5", "lib": [ "es5", "es2015.promise" ]
to:
"target": "es6", "lib": [ "es6" ]
and the error went away.
Note: For VS Code I needed to reload the window for IntelliSense to recognize the change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With