泛型函数
function getData4<T>(value: T): T {
return value;
}
泛型类
// 定义
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;
}
}
// 使用
const min = new minClass2<string>()
泛型接口
// 定义
interface ConfigFn2 {
<T>(value:T):T;
}
// 使用
var getData:ConfigFn2 = function<T>(value:T):T{
return value;
}
泛型约束
interface hasLength {
length: number
}
function test<T extends hasLength>(arg: T) {
console.log(arg.length)
}