Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generator function in typescript

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

like image 410
anandaravindan Avatar asked Mar 07 '17 18:03

anandaravindan


People also ask

Which is the correct way to declare a generator function?

The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

What is the use of generator function in JavaScript?

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.

What is the function of generator?

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.

How do you call a function from a normal generator?

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.


2 Answers

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++;     }    } 
like image 75
Bergi Avatar answered Sep 23 '22 13:09

Bergi


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.

like image 44
vossad01 Avatar answered Sep 23 '22 13:09

vossad01