EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript generator

TypeScript generator

Updated April 6, 2023

TypeScript generator

Introduction to TypeScript generator

In TypeScript, we have one special type of function, which is known as a generator. By the use of a generator in TypeScript, we can control the execution of the function in TypeScript. It comes up with so many extra features than a normal function in TypeScript. The generator can resume, stop, yield the function execution; it totally depends upon the caller’s choice. In short, by the use of generators in TypeScript, we can control the flow of function in the application. In the coming section, we will discuss more the internal working of the generator in detail for its better usage in our application.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

As discussed, generators are nothing but a special type of function in TypeScript, and its execution totally depends upon the caller of the function. Let’s have a look at its syntax for a better understanding of its implementation during the application; see below;

function* function_name() {
// our logic goes here ..
}

As you can see in the above lines of code, we are declaring syntax to use the generator in TypeScript; for this, we are using the asterisk symbol just after the function keyword in TypeScript. Inside this, we can simply define the function body like any other normal function in TypeScript. Let’s see one practice syntax for beginners for better usage see below;

function* myGenrator() {
// logic 1
// logic 2
}

In the coming section, we will see its internal working in detail, where we will see how to implement it in our application and use it.

How the generator work in TypeScript?

As of now, we already know that generator is used to control the program execution; its all control depends upon the caller who calls it. By the use of it, we can stop function execution, pause, resume and yield the value, etc. By using a generator, yield plays an important role here; without it, we cannot actually use the generator to execute. In this section, we will see its internal working and how to invoke it. Let’s see its working in detail.

Declaring a generator function: To declare a generator function in TypeScript, we use an asterisk symbol just before the function keyword in TypeScript. In a normal function declaration, we have only a function keyword associate with the function name, but in the generator, our function keyword bind with the asterisk symbol. Below sees the function declaration for the generator in TypeScript:

Example:

function* demo(){}

But inside this generator, we are bound to use the yield expression. This is important because it will transfer the control to the caller object; also, it will return the result to the caller object in TypeScript. After the function declaration, we can define its body as a swell, just like the normal function in TypeScript. But we have some rules while calling the generator function in TypeScript that we will discuss in the coming section of the tutorial.

How to use the generator in TypeScript?

As we discussed, it is very simple to define a generator in TypeScript but to call it; we have to have a look at some of the standards defined by the typescript language. We have to perform one more additional step to call the generator in TypeScript; we cannot call them like normal function in TypeScript. We have to use iterators for that to execute it. Suppose we have just called the generator function after defining it, but in the case of the generator, we are only calling the function, not the body of the function. Its body will not be executed until we use iterators for that; in this case, iterators will do this job. Generators internally support iterators, and by the use of them, we can execute the body of the generator.

Lets’ see one sample example for beginners to understand their working and implantation in more detail for better usage in the application without error; see below;

Example:

function* demogenerator(mynum:any) {
//logic here
for(var z = 0; z < mynum.length; z++) {
yield mynum[z];
}
}
var mydemoarray = [400, 500, 600, 700, 800, 900];
var myitr = demogenerator(mydemoarray);
console.log(myitr.next());

In the above lines of code, we are trying to implement a generator in TypeScript. In the first line of code, we create one generator function that will return the value from the passing array. Also, inside this generator function, we are using the yield keyword to return the result to the caller function. We can yield anything from the generator function; whether it is a string, number, or any other object depends upon the requirement. After that, we call the generator function. We have also created one array named ‘mydemoarray’, which contains all the elements we want the generator function to return on calling it. To call it, we have to follow two steps which are mentioned below;

1) Call function and pass the required parameter inside it, if any.

2) After this, we have to use iterators to execute its body. Without it, we will not get any output from the generator function. For this, we have to use the next() method from the iterator library.

Examples

1) In this example, we are trying to implement a generator in Typescript and try to print the values from the array. Here also, we have created only one instance of the generator function* and calling next() for the number of times to point it to the next element from the array.

Example:

function* demogenerator(mynum:any) {
//logic here
console.log("generator called !!");
for(var z = 0; z < mynum.length; z++) {
yield mynum[z];
}
}
console.log("Demo to show generator in typescript !!!");
var mydemoarray = [400, 500, 600, 700, 800, 900];
var myitr = demogenerator(mydemoarray);
let result1 = myitr.next();
let result2 = myitr.next();
let result3 = myitr.next();
let result4 = myitr.next();
let result5 = myitr.next();
let result6 = myitr.next();
console.log("printing result ::: ");
console.log("result one is  ::" );
console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);
console.log(result5);
console.log(result6);

Output:

TypeScript generator output 1

TypeScript generator output 2

Rules and regulation for the generator in TypeScript

There are several rule and regulation to use generator function in TypeScript, which we will discuss below;

1) To define the generator function in TypeScript, we have to use the * ‘asterisk’ symbol with the function keyword in TypeScript.

2) Also, we have to use yield expression inside the generator function to return the result and give control back to the caller function in TypeScript.

3) We cannot call generator function just like normal function in TypeScript; we have to use the iterator next() method to execute the body of the generator function in TypeScript.

4) We can control the generator function in TypeScript.

Conclusion

By the use of it, we can control the function execution in the application. They are very easy to use and implement, just like any other function in TypeScript; we just have to use the ‘*’ symbol before the function keyword while declaring it. We can pause, stop, resume the generator function as per the need.

Recommended Articles

We hope that this EDUCBA information on “TypeScript generator” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript typeof
  2. TypeScript Dictionary
  3. TypeScript Versions
  4. TypeScript Functions
All in One Excel VBA Bundle
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
Financial Analyst Masters Training Program
2000+ Hours of HD Videos
43 Learning Paths
550+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Data Science Bundle
2000+ Hour of HD Videos
80 Learning Paths
400+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle
5000+ Hours of HD Videos
149 Learning Paths
1050+ Courses
Verifiable Certificate of Completion
Lifetime Access
Primary Sidebar
All in One Software Development Bundle5000+ Hours of HD Videos | 149 Learning Paths | 1050+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program2000+ Hours of HD Videos | 43 Learning Paths | 550+ Courses | Verifiable Certificate of Completion | Lifetime Access
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more