function getData<T>(value: T):T {return value}
getData<number>(123)
getData<string>('123')
class MinClass {public list:number[] = [];
add (num:number) {this.list.push(num)
}
min():number {var minNum = this.list[0]
for (let i=0;i<this.list.length;i++) {if (minNum > this.list[i]) {minNum = this.list[i]
}
}
return minNum
}
}
class MinClass2<T> {public list:T[] = [];
add (num:T):void {this.list.push(num)
}
min():T {var minNum = this.list[0]
for (let i=0;i<this.list.length;i++) {if (minNum > this.list[i]) {minNum = this.list[i]
}
}
return minNum
}
}
let minNum = new MinClass2<number>() // 实例化类,并制订类的 T 代表的类型是 number
minNum.add(1)
minNum.add(2)
minNum.add(3)
console.log(minNum.min()) // 1
// 类作为参数束缚传入数据
class User {
username: string | undefined;
password: string | undefined;
}
class MysqlDB {add(user: User):boolean {console.log(user)
return true
}
}
let user = new User()
user.username = 'z'
user.password = '123456'
let mysql = new MysqlDB()
mysql.add(user)
// 泛型类
class MysqlDB2<T> {add(user: T):boolean {console.log(user)
return true
}
}
class User2 {
username: string | undefined;
password: string | undefined;
}
let user2 = new User2()
user2.username = 'z'
user2.password = '123456'
let mysql2 = new MysqlDB2<User2>()
mysql2.add(user2)