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
}
]
}
*/
本文介绍了如何在JavaScript中使用自定义泛型类MyArray进行数组操作,如添加元素和打印,同时展示了如何通过类型约束限制T的范围。实例中演示了泛型方法map的应用,并通过HasWeight接口约束了数据类型。最后,通过MyArray<WeightNumber>实例展示如何对对象按权重排序。
123

被折叠的 条评论
为什么被折叠?



