1、自定义泛型
class MyArray<T>{
data:T[] = []
add(t:T){
this.data.push(t)
}
print(){
console.log(this.data)
}
//MyArray<number>.map<string>(f: (v: number) => string): string[]
//定义一个泛型方法
//U:未知的返回类型
//T:输入参数的类型
map<U>(f:(v:T) => U):U[]{
return this.data.map(f)
}
}
const a = new MyArray<number>()
a.add(1)
a.add(3)
a.add(5)
console.log(a.map(v=>v.toExponential())) 、 ["1e+0", "3e+0", "5e+0"]
2、约束T的类型范围
interface HasWeight {
weight:number
}
class MyArray<T extends HasWeight> {
data:T[] = []
add(t:T){
this.data.push(t)
}
map<U>(f:(v:T) => U):U[]{
return this.data.map(f)
}
print(){
console.log(this.data)
}
sortByWeight(){
this.data.sort((a,b) => a.weight - b.weight)
}
}
class WeightNumber {
constructor(public weight:number){}
}
const a = new MyArray<WeightNumber>()
a.add(new WeightNumber(33))
a.add(new WeightNumber(45))
a.add(new WeightNumber(76))
a.sortByWeight()
console.log(a)
/*
//输出结果:
MyArray: {
"data": [
{
"weight": 33
},
{
"weight": 45
},
{
"weight": 76
}
]
}
*/