Generic is to solve the repeat usage of class, interface, and method. And support the undecided data type.
// defined type, could only return defined type, no others
function getData(value: string): string{
return value;
}
// defined with any, could return with any value, actually without any constrain
function getData(value: any): any{
return value;
}
Therefore the better way is to unify the passed value and returned value with the same type. Then we have the Generic.
function getData<T>(value: T): T{
return value;
}
getData<number>(123); // return 123
getData<number>('123'); // fail, cause type not identical
Any Uppercase Letter could be valid, but normally T is taken.
Below there is one case to explain the Generic, first this example is with normal typescript without generci.
// Finding the minimum value
class MinClass{
public list:number[ ] = [ ];
add(num:number){
this.list.push(num);
}
min( ): number{
var minNum = this.list[0];
for(var i = 0; i < this.list.length; i ++){
if(minNum > this.list[i]) {
minNum = this.list[i];
}
}
return minNum;
}
}
var m = new MinClass();
m.add(2);
m.add(4);
m.add(23);
m.min(); // 2
Then we modify this example with Generic.
class MinClass<T>{
public list: T[ ] = [ ];
add(num: T){
this.list.push(num);
}
min( ): T{
var minNum = this.list[0];
for(var i = 0; i < this.list.length; i ++){
if(minNum > this.list[i]) {
minNum = this.list[i];
}
}
return minNum;
}
}
var m1 = new MinClass<number>(); // Instance
m1.add(1);
m1.add(2);
m1.add(23);
m1.min(); // 1
var m2 = new MinClass<string>();
m2.add('a');
m2.add('c');
m2.add('v');
m2.min( ); // a here using ASCII for comparing the value.
Generic
is to solve therepeat
usage ofclass
,interface
, andmethod
. And support the undecided data type.Therefore the better way is to unify the passed value and returned value with the same type. Then we have the
Generic
.Any Uppercase Letter
could be valid, but normallyT
is taken.Below there is one case to explain the Generic, first this example is with normal typescript without
generci
.Then we modify this example with
Generic
.Generic Interface
1. Method 1
2. Method 2