QiaoranC 2019-07-01
function getData1(value:string):string{ return value; } function getData2(value:number):number{ return value; } console.log(getData1('aa')); console.log(getData2(11));
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个类来实现
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());
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));