//泛型
function swap<A, B>([A, B]): [B, A] {
return [B, A];
}
const result = swap([1, 2]);
console.log(result)//[2,1]
//用泛型操作数组
function arrLen<T>(arr: T[]): T[] {
console.log(arr.length);
return arr;
}
const resultLen = arrLen([1, 2, 3]);//3
console.log(resultLen);//[1, 2, 3]
//用接口去约束泛型中所传入的值的类型
interface IWithLen {
length: number;
}
function arrLen<T extends IWithLen>(arr: T): T {
console.log(arr.length);
return arr;
}
arrLen([1, 2, 3]);//3
arrLen('string');//6
arrLen({length:10,num:100})//10
typescript中的泛型用法
最新推荐文章于 2023-01-20 16:00:39 发布