//泛型
//-- 1泛型要解决的问题
function ache(arg) {
return arg
}
//调用Ache
const result = ache('ff')
这样会发现变量丧失了类型 -
接下来做如下修改 发现变为string类型
function ache(arg:string):string {
return arg
}
//调用Ache
const result = ache('ff')
但是我们可能传的是number 类型 或者其他类型 那么接下来怎么处理呢?这时候泛型就来拯救我们了,
来看一下泛型的定义 :泛型是在我们定义接口和类的时候 我们不先指定具体的类型 而是在使用的时候
指定类型的一种特征。接下来这样修改代码
function ache<T>(arg:<T>):<T> {
return arg
}
//调用Ache
// const st:string = "String"
const result = ache("bbb")
类型变为string
function ache<T>(arg: T): T {
return arg
}
//调用Ache
const result = ache(123) //返回number类型 123
2 多个类型
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]]
}
const r = swap(['string', 123])