Why I need generic in Typescript


In below sample i use generic function:

function Identity<T>(arg: T): T[] {

    return arg;

I can write my method in this way :

  function loggingIdentity(arg) {
          return arg;

Both of method can accept any type value and return any value.what is benefit of using generic for above method ?
in other sample i have used generic for create a class:

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

I can create class and new object without using generic :

 class GenericNumber {
        add: (x, y);
    let myGenericNumber = new GenericNumber();
    myGenericNumber.zeroValue = 0;
    myGenericNumber.add = function(x, y) { return x + y; };

in c# language type determination is mandatory but in typescript is optional and We can declare a property or variable or parameter without type determination and they can be of any type.

I would be happy if anyone describe me importance and all benefit of using generic in typescript.


You can use any everywhere in TypeScript. But then you’re basically using JavaScript, and don’t have any type safety anymore, which is the reason why TypeScript exists in the first place. Isn’t it nice that the IDE tells you what an array is supposed to contain, and refuses to let you push a string into an Array<number>?



In all your examples, T can be any type, but all Ts are the same type. This is important: Let’s consider your GenericNumber class. It has an add method, that takes two arguments of type T and returns a T. This might be a add(x:number, y:number):number or a add(x:string, y:string):string – but never a add(x:string, y:Foo):boolean.

Also, the typescript compiler will know that if you pass in two numbers, the function will return a number as well. This can be valuable information at the callsite of the function.

I also recommend you read the chapter on generics in the typescript handbook – the first section “Hello World of Generics” basically answers your question.