Table of contents
1.
Introduction
2.
Generics Syntax
3.
How it works
4.
Generic Class
5.
Use Case
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Generic Classes in TypeScript

Author Parth Jain
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In a bank, to open an account, we must fill out a form. The bank has different forms based on gender. Therefore, the bank has to maintain 11 documents for all 11 genders to support all 11 types of customers. However, instead of creating 11 different forms, the bank can create a single form with an input field where the customer can manually mention their gender. This saves the trouble of maintaining 11 different documents and provides more flexibility. This is the principle behind Generic Classes.
Typescript’s Generic Classes allow us to create reusable blocks of code while providing the ability to use different types. Let’s consider a case where we want a class to work for numbers and strings. We will have to create two separate classes to support both data types to make this possible. However, using generic classes, we don’t have to do that. Instead, we create a generic class capable of accepting both data types.
When a class is made generic, it gains the ability to enforce the type of data passed to it, making the code more flexible and negating redundancy.
We can also accomplish this by using any data type. However, this makes us lose the information passed for a particular object of that class. 
Therefore, Generic Classes help us create reusable and cleaner code without losing the type information of an object. 

Generics Syntax

Before getting into the practical application of Generic Classes, it is crucial to understand its syntax.
Generics appear inside the angle brackets enclosing the letter T like <T>, where T represents a passed-in data type. <T> can be comprehended as a generic of type T.T operates in the same way that parameters work in functions, as a placeholder for a type that will be declared when the structure of a class or function is created. Therefore, the generic types specified inside angle brackets are generic type parameters. Multiple generic types can be made for a single structure such as <T, K, A>.

How it works

function testFunction <T> (argument:T):T {
 return argument;
}
let variable1=testFunction<number>(1);
let variable2=testFunction<string>("Hello");

This Generic Function accepts an argument of type T and returns that type T. 
Here,

testFunction <T> // T is Generic Type Parameter 
 (argument:T) // Is item parameter of Type T
 :T //is the return value of type T

Typescript can now initialize T as of any type that is specified. In the above example, variable1 is of type number and contains 1. Variable2 is a string that contains the string “Hello.”

Generic Class

Now that we are familiar with the Generics syntax, it is time to learn about Generic Classes.
Implementing Generic Classes is the same as implementing a typical class, as all we do is introduce the type parameter. We use the angle brackets and to enclose the type parameter. The type parameter is usually specified as <T>. However, it is not compulsory as we can set anything as a type parameter.
In Generic Classes, we can pass more than one parameter. We need to specify a generic type parameter for each argument.

class GenClass <T,U> {
    firstVal: T;
    secondVal: U;
   setKeyValue(firstVal: T, secondVal: U): void {
       this.firstVal = firstVal;
       this.secondVal = secondVal;
   }
   display():void {
       console.log(`First Value = ${this.firstVal}, Second Value = ${this.secondVal}`); }
}
let a=new GenClass <number,number> ();
let b=new GenClass <string,string> ();
let c=new GenClass <number,string> ();
let d=new GenClass <boolean,number> ();

a.setKeyValue(9,8);
b.setKeyValue("Coding","Ninjas");
c.setKeyValue(19,"December");
d.setKeyValue(true,1);

a.display();
b.display();
c.display();
d.display();

The “GenClass” is an example of a Generic Class where T and U are generic parameters that can hold any data type in the above example. During the initialization of a,b,c, and d, we specified the type of data that each object of “GenClass” will hold, and Typescript defines the specified type for each object. This Generic Class reduces the line of code exponentially as instead of creating four different classes, we only made 1.

Use Case

While Generic Classes are instrumental and easy to implement, Their usage is often questioned. Hence, to clarify the Generic Classes concept, let us discuss a use case. 
Consider a class that can accept both string and number type arguments, and if the given arguments are numbers, we want the sum of numbers to be displayed, and in the case of strings, we want a string concatenation.

class GenericClass<T,K> {
 zeroValue: T;
 add(x: K, y: K) : K {
   return x + y;
 };
 }
let a = new GenericClass<string,string>();
a.zeroValue = "This is string concatenation";

console.log(a.zeroValue);
console.log(a.add("Welcome to ","CN"));

let b = new GenericClass<string,number>();
b.zeroValue = "This is a Sum";

console.log(b.zeroValue);
console.log(b.add(10,52));

Output:

This is string concatenation
Welcome to CN
This is a Sum
62


Check out this problem - Redundant Braces

FAQs

  1. Why are generics used in TypeScript?
    Generics help us identify the data type of an argument whose return value is undefined until consumed later.
     
  2. What is T type in TypeScript?
    T is the generic data type in TypeScript.It is used as a default value for a generic type. However, it is not compulsory and can be changed as per the user’s requirement.

Key Takeaways

We learned about Generic Classes in Typescript and how their syntaxes work from this article. We also discovered their purpose and how Generic Classes make managing code much more effortless. However, this isn’t enough, as there is always much more to explore and learn about this vast field of Web Development. To know more about Typescript and its intricacies, check out the articles on Typescript or enroll in our highly curated Web Development course.

 

Live masterclass