1、泛型
class MyArray<T> {
data: T[] = []
data(t: T) {
this.data.push(t)
}
print(){
console.log(this.data)
}
}
const a = new MyArray<string>()
a.add('abc')
a.add('def')
a.print()
定义多个泛型
class MyArray<T> {
data: T[] = []
data(t: T) {
this.data.push(t)
}
map<U>(f: (v: T) => U): U[]{
return this.data.map(f)
}
print(){
console.log(this.data)
}
}
const a = new MyArray<number>()
a.add(1)
a.add(2000)
a.add(30000)
console.log(a.map( v => v.toExponential()))
接口约束泛型
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 WeightedNumber{
constructor(public weight: number){}
}
const a = new MyArray<WeightedNumber>()
a.add(new WeightedNumber(10000))
a.add(new WeightedNumber(200))
a.add(new WeightedNumber(30000))
a.sortByWeight()
console.log(a)