赞
踩
class minClass { public list:number[] = [] add(num:number) { this.list.push(num) } minNumber():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(2) console.log(m.minNumber()) }
class minClass2<T> { public list:T[] = [] add(value:T)void { this.list.push(value) } minNumber():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 minClass2<number>(); m.add(1); m.add(2); var m2 = new minClass2<string>(); m2.add('a'); m2.add('b');
// 定义一个函数接口 interface ConfigFn { (v1:string,v2:string):string; } let setData:ConfigFn = function(v1:string,v2:string):string { return v1 + v2; } // 定义泛型方法 interface ConfigFn2 { <T>(value:T):T; } let getData:ConfigFn2 = function<T>(value:T):T { return value } // 定义泛型接口 interface ConfigFn3<T>{ (value:T):T; } let myGetData:ConfigFn3<string> = function<T>(value:T):T{ return value; }
// User类来映射数据库字段 class User { userName:string | undefined; password:string | undefined; } class MySqlDB { add(user:User):boolean { console.log(user) return true } } class Person { name:string | undefined; age:number | undefined; id:number | undefined; constructor(params:{ name:string | undefined, age:number | undefined, id?:number | undefind }) { this.name = params.name; this.age = params.age; this.id = params.id; } } let p = new Persion({ name:'张三', age:20 })
function test<T>(arg:T):T {
return arg;
}
let out = test<string>('yivi');
let out = test('yivi');
function test<T>(arg:T):T { console.log(arg.length) // error,arg的类型为T,无明确指示方法,因此报错 return arg; }
function test<T>(args : T[]):T[] {
console.log(args.length)
return args;
}
function test<T>(args:Array<T>):Array<T> {
console.log(args.length)
return args;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。