Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Generics in Typescript?

I am totally new to typescript and never into c# or java before. So even if I read the instruction on official typescript website, I really do not understand the real use of Generics.

Here is the simple example of Generics. What is the real benefits of doing this below?

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

var output = identity<string>("myString");

without Generics, I can just do this way below (or I can use Interfaces to make sure to pass specified arguments.)

function identity(arg: any): any  {
    return arg;
}
var output = identity("myString");

Any advice would be appreciated. Thank you

like image 743
Ban Avatar asked Jan 27 '16 01:01

Ban


2 Answers

Just going from your basic example:

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

Having a generic here enforces a constraint between the argument (arg:T) and the return type : T{. This allows the compiler to infer the return type from the argument as shown below:

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

let str = identity('foo');
// str is of type `string` because `foo` was a string

str = '123'; // Okay;
str = 123; // Error : Cannot assign number to string
like image 132
basarat Avatar answered Nov 01 '22 11:11

basarat


Generics in TypeScript

Using generics is a lot safer than using the any type in such situations. Let me show you the file contents:

Without Generics

In the below code randomElem function returning the string from the string array. In randomColor function we are changing the type as number, but it will not produce any error during compile time (or) run time.

randomElem(theArray: any): any {
    return theArray[0]; // returning a string.
}

randomColor() {
    let colors: string[] = ['violet', 'indigo', 'blue', 'green']; // String array
    let randomColor: number = this.randomElem(colors);
}

Without Generics Reference Image

With Generics

But when using the generic function if we are try to change the type then we will get the error while compile itself.

  randomElem<T>(theArray: T[]): T {
    return theArray[0];
  }

  randomColor() {
    let colors: string[] = ['violet', 'indigo', 'blue', 'green']; // String array
    let randomColor: number = this.randomElem(colors); // Produce Error
  }

With Generics Reference Image

This proves that using generics is a lot safer than using the any type in such situations :).

like image 2
Satham hussain.m Avatar answered Nov 01 '22 13:11

Satham hussain.m