a blog for those who code

Tuesday, 19 May 2015

Generics in TypeScript

In this post we are going to discuss about generics in TypeScript. Generics are the code templates that can be used throughout your application. Like Interfaces in Typescript, Generics are also available only in compile-time which means there is no concept of Generics in compiled JavaScript.

As mentioned Generics are the code templates that relies on type <T>, that can be used throughout your code bases. The importance of using Generics are cod is not duplicated for multiple types of data which means it provides us more flexibility when working with different data types. It can use as a replacement of 'any', thus we can minimize the use of 'any' data type.

Generics Example :

class GenericsExample<T> {
    value : T;
    setValue(value : T) {
        this.value = value;
    getValue() : T {
        return this.value;

var gen1 = new GenericsExample<string>();
gen1.setValue("Hello World");

var gen2 = new GenericsExample<number>();

var gen3 = new GenericsExample<boolean>();

In this example we have used <T> which is a Generic Type Variable. Now the question is how do you tell TypeScript what exactly T is. The answer is when we are instantiating a class using new GenericsExample<string>(); we are specifying the type of T (string in this case). Now you can understand the beauty of Generics is that if we need a same class to behave similarly with different data type we do not have to write it multiple times we can simply use Generics.

One more thing to know about Generics in TypeScript is Generics Constraint. For example you have the following code :

interface ITest { }
class Test<T extends ITest> { }

The above code means that T has to implement ITest. In simple terms it will restrict the type of T to anything that implements ITest. The importance of this is that you cannot really pass any datatype, but you just have to pass something specific (in this case its going to be ITest).

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment