Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

typescript

What are Generics in TypeScript and How to use Generics

TypeScript is a statically typed superset of JavaScript that provides developers with many powerful features. One such feature is generics, which allows developers to create reusable code that can work with different types of data. In this blog post, we will explore generics in TypeScript and explain how they work.

What are Generics in TypeScript?

Generics are a way to create reusable code that works with different types of data. With generics, you can write a function or a class that can work with different data types without repeating the code for each data type.

Generics are similar to function parameters in that they allow you to define a placeholder for a type. For example, consider the following function:

function someTask(arg: any): any {
    return arg;
}

This function takes an argument of any type and returns it. While this function works, it loses type safety. We can use generics to make this function more type-safe:

function someTask<T>(arg: T): T {
    return arg;
}

In this code, T is a type parameter. You can use any letter instead of T in here. When we call ‘someTask‘ method, we can specify the type that T should represent. For example, we can call ‘someTask‘ with a string:

let output = someTask<string>("Hello world!");

In this case, T is replaced with number, and the function returns a number.

Creating a Generic Class

We can also create generic classes in TypeScript. Check the following class:

class Queue {
    private data = [];
    push(item) {
        this.data.push(item);
    }
    pop() {
        return this.data.shift();
    }
}

This class represents a simple queue data structure. However, it only works with values of type any. We can use generics to make this class more flexible:

class Queue<T> {
    private data = [];
    push(item: T) {
        this.data.push(item);
    }
    pop(): T {
        return this.data.shift();
    }
}

In this code, we’ve added a type parameter T to the Queue class. We’ve also specified the type of the push method’s argument as T. Finally, we’ve specified the return type of the pop method as T.

Now, we can create a Queue object that works with a specific type:

let numberQueue = new Queue<number>();
numberQueue.push(0);
numberQueue.push(1);
numberQueue.push(2);
console.log(numberQueue.pop().toFixed()); // Outputs 0
console.log(numberQueue.pop().toFixed()); // Outputs 1
console.log(numberQueue.pop().toFixed()); // Outputs 2

let stringQueue = new Queue<string>();
stringQueue.push("Hello");
stringQueue.push("World");
console.log(stringQueue.pop().toUpperCase()); // Outputs "HELLO"
console.log(stringQueue.pop().toUpperCase()); // Outputs "WORLD"

In this code, we’ve created a Queue object that works with numbers, and another Queue object that works with strings.

Conclusion

Generics are a powerful feature of TypeScript that allow developers to create flexible and reusable code. By using generics, you can write functions and classes that work with different types of data without repeating code. With the knowledge presented in this blog post, you should now have a better understanding of how generics work in TypeScript and how they can be used in your own code.