# TypeScript 泛型
# 泛型示例
class Type<T>{
name: T
salary: number
constructor(name: T,salary: number) {
this.name = name
this.salary =salary
}
set MyName(n: T){
this.name = n
}
get MyName(){
return this.name
}
}
const type1 = new Type<number>(1, 2)
const type2 = new Type<string>('hedon', 2)
# 约束泛型
interface HasWeight {
weight:number
}
// T 必须有 HasWeight 中有的属性
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)
}
}