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
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
Using generics is a lot safer than using the any type in such situations. Let me show you the file contents:
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
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 :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With