Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
What are Generics in TypeScript ?
Next article icon

What are Generics in TypeScript ?

Last Updated : 14 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will try to understand all the facts as well as the details associated with Generics in TypeScript along with some coding examples.

Generics in TypeScript:

  • Whenever any program or code is written or executed, one major thing one always takes care of which is nothing but making reusable components which further ensures the scalability and flexibility of the program or the code for a long time.
  • Generics, thus here comes into the picture as it provides a user to flexibly write the code of any particular data type (or return type) and that the time of calling that user could pass on the data type or the return type specifically.
  • Generics provides a way to make the components work with any of the data types (or return types) at the time of calling it for a certain number of parameters (or arguments).
  • In generics, we pass a parameter called type parameter which is put in between the lesser sign (<) and the greater sign (>), for example, it should be like <type_parameter_name>.

Syntax for writing Generics:

Following syntax we may use to add generics into our pre-written piece of code (this is the syntax of using Generics in functions):

function function_name <type_parameter>       (parameter_name : data_type_parameter)       : return_type_parameter {          // Rest code......      }

Advantages of using Generics in TypeScript:

Following are the list of advantages that generics provide in TypeScript:

  • By using generics we may safely store a single type of object without storing the other types too.
  • By using generics we need not implement the typecasting of any variable or function at the time of calling.
  • Generics are usually checked at the compile time so no issue exists in runtime.

Now after understanding all of the above-mentioned details which are associated with Generics, let us move forward and see some of the following code examples for a better understanding of Generics-

Example 1: In this example, we will simply see how we may try to create a generic function with generic parameters inside it and further how we may call that generic function with generic parameters.

JavaScript
function displayData <type_parameter>      (parameter :type_parameter) : type_parameter{       return parameter;   }  let result1 = displayData <string> ("GeeksforGeeks"); let result2 = displayData <string> ("Hello World !!"); let result3 = displayData <number> (1234567890);  console.log(result1); console.log(result2); console.log(result3); 

Output:

GeeksforGeeks  Hello World !!  1234567890

Example 2: In this example, we may try to create a generic function with a generic return type of array along with the generic parameters (that too of generic array data type) passed in it and further how we may call that generic function which will return the array as the result.

JavaScript
let displayResult = <type_parameter>      (data_item : type_parameter[]) : type_parameter[] => {     return new Array <type_parameter>().concat(data_item);   }  let numbersArray = displayResult<number>     ([50 , 60 , 80 , 90]);      let stringArray = displayResult<string>     (["Hello World", "GeeksforGeeks"]);  console.log(numbersArray); console.log(stringArray);  numbersArray.push(100); stringArray.push("Apple");  console.log(numbersArray); console.log(stringArray); 

Output:

[ 50, 60, 80, 90 ]  [ 'Hello World', 'GeeksforGeeks' ]  [ 50, 60, 80, 90, 100 ]  [ 'Hello World', 'GeeksforGeeks', 'Apple' ]

Example 3: In this example, we will be creating some multi-generic-type variables and will further see how we may call them inside our function which we are making for the execution.

JavaScript
let displayResult = <type_1, type_2>      (id : type_1, name : type_2) => {       return id + " - " + name;     }  let data_1 = displayResult<number,      string>(2000, "GeeksforGeeks");      let data_2 = displayResult<number,      string>(2001, "Hello World !!");  console.log(data_1); console.log(data_2); 

Output:

2000 - GeeksforGeeks  2001 - Hello World !!

Reference: https://www.typescriptlang.org/docs/handbook/2/generics.html


Next Article
What are Generics in TypeScript ?

A

amansingla
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks-Premier-League-2022

Similar Reads

    What are TypeScript Interfaces?
    TypeScript interfaces define the structure of objects by specifying property types and method signatures, ensuring consistent shapes and enhancing code clarity.Allow for optional and read-only properties for flexibility and immutability.Enable interface inheritance to create reusable and extendable
    4 min read
    What are Hybrid Types in TypeScript?
    Hybrid types are used by TypeScript to refer to types that combine different things such as objects, functions, arrays etc. In this article, we will learn more about Hybrid Types in TypeScript.What are Hybrid Types in TypeScript?In TypeScript, using interfaces or type aliases we can define hybrid ty
    2 min read
    TypeScript Generic Classes
    Generics in TypeScript allow us to create reusable and type-safe components. Generic classes help in defining a blueprint that can work with different data types without sacrificing type safety. They enable better code reusability and flexibility by allowing us to define type parameters that will be
    5 min read
    What is Type Erasure in TypeScript?
    TypeScript is a very mighty superset of JavaScript, which adds static typing to the language and allows developers to catch errors early on as well as write more maintainable code. This being said a TypeScript type system erases type information at compile time (or during the compilation), a phenome
    4 min read
    What is Recursive Generic in TypeScript ?
    In TypeScript, a recursive generic is a type that refers to itself within its definition, enabling the creation of data structures or types containing references to the same type within their structure. This capability proves invaluable when dealing with nested or hierarchical data structures like t
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences