TypeScript--泛型
泛型
声明一个方法,同时返回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());
泛型接口
未使用泛型
interface ConfigFn{ (value1:string,value2:string):string; } var setData:ConfigFn = function(value1:string,value2:string):string{ return value1+value2; } console.log(setData('name','list'));
使用泛型
interface ConfigFn{ <T>(value:T):T; } var setData:ConfigFn= function<T>(value:T):T{ return value; } console.log(setData<string>('aa')); console.log(setData<number>(123));
相关推荐
xiaoxiaoCNDS 2020-06-25
iconhot 2020-05-26
zhangxiafll 2020-11-13
anglehearts 2020-08-17
TreasureZ 2020-06-16
lantingyue 2020-05-31
luohui 2020-04-29
fraternityjava 2020-04-29
yicuncuntu0 2020-04-19
Justhavefun 2020-02-21
alicelmx 2020-02-13
iconhot 2020-01-28
yicuncuntu0 2019-12-18
wxy0 2019-12-09
丁一鸣的CSDN 2011-06-25
iosJohnson 2019-11-05