泛型
声明一个方法,同时返回 string,number 类型
问题
function getData1(value:string):string{
return value;
}
function getData2(value:number):number{
return value;
}
console.log(getData1(‘aa’));
console.log(getData2(11));
利用 any 来解决, 但是放弃了类型教验
function getData(value:any):any{
return value;
}
console.log(getData(‘aa’));
console.log(getData(11));
利用泛型
function getData<T>(value:T):T{
return value;
}
console.log(getData<number>(123));
console.log(getData<string>(‘aaa’));
获取数组最小值
未使用泛型
要同时实现 string,number, 要写 2 个类来实现
number
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(1);
m.add(6);
m.add(2);
m.add(11);
console.log(m.min());
string
class MinClass{
public list:string[]=[];
add(num:string){
this.list.push(num);
}
min():string{
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(‘a’);
m.add(‘c’);
m.add(‘b’);
console.log(m.min());
泛型
一个类,同时实现 string,number
class MinClass<T>{
public list:T[]=[];
add(num:T):void{
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 m = new MinClass<number>();
m.add(1);
m.add(6);
m.add(2);
m.add(11);
console.log(m.min());
var s = new MinClass<string>();
s.add(‘a’);
s.add(‘b’);
s.add(‘f’);
s.add(‘d’);
console.log(s.min());