function echo<T>(arg:T):T{
return arg
}
//使用<T>泛型 result类型会直接显示值, 如number 或 string
const result = echo(123)
//以下同理
function swap<T,U>(tuple:[T,U]):[T,U]{
return [tuple[0],tuple[1]]
}
const result2 = swap(['string',123]);
//约束泛型
interface IWithLenght{
length:number
}
//约束泛型必须有lenght属性, 不管是什么类型, 字符串或是数组
function echoWithLenght<T extends IWithLenght>(arg:T): T{
//如果不写extends IWithLenght, 拿不到length会报错
console.log(arg.length);
return arg;
}
//只要包含length属性即可
const str = echoWithLenght('str');
const obj = echoWithLenght({length:10});
const arr2 = echoWithLenght([1,2,3])
//会报错,
const arr4 = echoWithLenght(13)