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>.