Table of contents
1.
Introduction
2.
Why Generics are Important
3.
Multiple Arguments
4.
Generics Interfaces
5.
Generic Classes
6.
Generic Interface as Function Type
7.
FAQS
8.
Key Takeaways
Last Updated: Mar 27, 2024

TypeScript Generics

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Typescript is a programming language that Microsoft developed. It is like a superset of the more commonly used Javascript. Typescript is designed for the development of very large-scale applications. Since it is a superset of Javascript, existing Javascript programs are also valid in Typescript. Typescript files are saved with the .ts extension.

Generics is a Typescript tool that provides the user ways to create reusable components. Generics make components that allow the user to work with various data types. Generics ensures that the Typescript program is scalable for long-term use and makes sure it is flexible.

Let us look at an example of Generics to understand it better,

function numberOrString<T>(toCheck: T): T {    
    return toCheck;    
}    
let name = numberOrString<string>("CodingNinja");    
let num = numberOrString<number>( 1001 );  
console.log(name+ ", Type of variable is : " +typeof(name));  
console.log(num+ ", Type of variable is : " +typeof(num));  

To create a Generic Type function, we add the open and close angular brackets (<>) in front of the function name and pass a variable in the brackets. In our case, we have used T. In the above code snippet for the variable “name,” the input and return type of the function is a string, and for the variable “num,” the input and return type of the function is a number.

Why Generics are Important

Let us look at an example to understand the importance of Generics in Typescript,

function pushItems(items: any[] ) : any[] {  
    return new Array().concat(items);  
}  
let NumArr = pushItems([1, 2, 3]);  
let StrArr = pushItems(["Welcome", "Ninja"]);  
NumArr.push(4);
NumArr.push("Hello"); 
StrArr.push("Hello Ninja"); 
StrArr.push(4);   
console.log(NumArr); 
console.log(StrArr); 

In the above example, we have used any data type instead of Generics, but what if we only wanted the number values in NumArr and only string values in the StrArr. That’s where Generics come into action. Let’s see how we could have approached this task using Generics.

function pushItems<T>(items:T[]) : T[] {  
    return new Array<T>().concat(items);  
}  
let NumArr = pushItems<number>([1, 2, 3]);  
let StrArr = pushItems<string>(["Welcome", "Ninja"]);  
NumArr.push(4);
NumArr.push("Abcd"); 
StrArr.push("Hello Ninja"); 
StrArr.push(50);   
console.log(NumArr); 
console.log(StrArr); 

As is clear from the above example, using Generics, we can restrict the addition of a string value to the NumArr and a number value to the StrArr.

function pushItems<T>(items:T[]) : T[] {  
    return new Array<T>().concat(items);  
}  
let NumArr = pushItems<number>([1, 2, 3]);  
let StrArr = pushItems<string>(["Welcome", "Ninja"]);  
NumArr.push(4);
StrArr.push("Hello Ninja");   
console.log(NumArr); 
console.log(StrArr); 

Multiple Arguments

We can also pass multiple arguments using Generics. Let us look at this example to understand this concept better,

function displayProd<T, U, W>(id:T, name:U, price:W): void {   
  console.log("Product Id: "+id+ "\nProduct Name: "+name+ "\nProduct Value: "+price);    
}  
displayProd<number, string>(1, "Pen", "20");  

As is clear from the above example, we can pass multiple Generic type arguments in a function.

Generics Interfaces

Generics can also be implied to the interfaces in Typescript. Let us look at an example to understand Generics in interfaces better,

interface Product {  
    name: string  
    price: number  
}  
interface Quantity extends Product {  
    qty: number  
}  
function printProduct<T extends Quantity>(Input: T): void {  
    console.log(`Name: ${Input.name} \nPrice: ${Input.price} \nQuantity: ${Input.qty}`);  
}  
let prod: Quantity = {  
    name: 'Eraser', price: 10, qty: 'Cricket Player'  
}  
printProduct(prod);  

In the above example, the input types for the function printProduct solely depend on the variables declared in the declared interfaces.

Generic Classes

As we saw, we can easily apply Generics using interfaces. Similarly, we can also apply generics to Typescript classes. Let us see how

class ProductInfo<T,U>  
{   
    private Id: T;  
    private Name: U;  
    setValue(id: T, name: U): void {   
        this.Id = id;  
        this.Name = name;  
    }  
    display():void {   
        console.log("ID: "+this.Id+"\t\tName: "+this.Name);
    }  
}  
let product_1 = new ProductInfo<number, string>();  
product_1.setValue(11, "Laptop");  
product_1.display();  
let product_2 = new ProductInfo<string, string>();  
product_2.setValue("12", "Stylus");  
product_2.display();  

The variables Id and Name are of Generic type, and their data type can change according to user convenience.

Generic Interface as Function Type

Generics interfaces can also be used as function types in Typescript. Let us see an example to understand it better,

interface ProductInfo<T, U>  
{  
    (id: T, name: U): void;  
};  
function Product(id: number, name:string):void {   
    console.log('Id: '+ id + '\t\tName: ' + name)  
}  
let prod: ProductInfo<number, string> = Product;  
prod(11, "Laptop");  

FAQS

1. What are the advantages of Generics?

There are three main advantages of using generics.

  • If we use Generics, we don’t have to typecast any object.
  • Generics are checked at the compile time. Thus there are no runtime errors.
  • Only one type of object can be stored in Generics. 
     

2. What are Generics?

Generics is a Typescript tool that provides the user ways to create reusable components. Generics make components that allow the user to work with various data types. Generics ensures that the Typescript program is scalable for long-term use and makes sure it is flexible.

Key Takeaways

This Blog covered all the necessary points about Generics in Typescript, discussing in-depth its functionality and the methods of the appliance of Generics. And also its implementation in Typescript.

Don't stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.

Live masterclass