What is Generics in Typescript?

I am completely new to typescript and have never met in C # or java before. Therefore, even if I read the instructions on the official typescript website, I really do not understand the real use Generics.

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

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

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

without Generics, I can just do it below (or I can use interfaces to pass the specified arguments.)

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

Any advice would be appreciated. thank you

+5
source share
3 answers

Just go to your main example:

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

If there is a common limitation applies here (arg:T) : T{. , :

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
+3

var output any.

generics , output string.

0

TypeScript

, . :

randomElem . randomColor , () .

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);
}

Generics

, , .

  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
  }

Generics

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

0
source

Source: https://habr.com/ru/post/1626092/


All Articles