How to use Generic Class in TypeScript?

How to use Generic Class in TypeScript?

·

2 min read

TypeScript supports generic classes and functions just like other programming languages Java and c#.

We use generics for writing reusable and flexible code.

Generic classes allow us to create classes that can work with any type of data, and that makes our code more flexible and reusable, as we don't have to create different classes for different data types.

Define generic class:

A generic class takes type parameters in an angle bracket (<Type>) after the class name.

For example:

class DataStore<T> {
    data: T[];
    constructor(data: T[]){
        this.data = data;
    }

    setData(item : T):void{
        this.data.push(item);
    }

    getData(): T[] {
        return this.data;
    }
}

In the above example, we defined a class DataStore with the type parameter T. Here, the type parameter T can be any type.

When we create an object of this class, we specify the type of data it should store.

For example:

let numStore = new DataStore<number>([1,2,3]);
numStore.setData(5);
console.log(numStore.getData()); // [1,2,3,4]

let strStore = new DataStore<string>(["Apple","Banana"]);
strStore.setData("Mango");
console.log(strStore.getData()); //[Apple, Banana, Mango]

In the above code snippet, we are creating two objects of the DataStore class, numStore object stores numbers and strStore object stores string data types.

There are many scenarios where generic classes make our code reusable and flexible.

Let's take one more example.

class Store<T> {
       contents: T[] = [];

       add(object: T) {
         this.contents.push(object);
       }

       remove() {
         return this.contents.pop();
       }
 }

interface IShoes{
    size:number;
    price: number;
}

interface IJeans{
    color:string;
    price: number;
    size: 'S' | 'M' | 'L'
}


// // We can create a store just for shoes by passing in the
// // type IShoes when we create a new shoesStore:
 const shoesStore= new Store<IShoes>();

// // Now we can add or remove shoes to the store:
 shoesStore.add({ size: 8, price: 1200 });
 const mySock = shoesStore.remove();

// // Create a store for Jeans:
 const jeansStore = new Store<IJeans>();
 jeansStore.add({ size: "M",color:'blue', price:200 });

// we could even crete a store
// which mixes both jeans and shoes by using a union:

 const mixStore = new Store<IShoes | IJeans>();