共计 1146 个字符,预计需要花费 3 分钟才能阅读完成。
泛型:能够反对不特定的数据类型 要求:传入的参数和返回的参数统一
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)
正文完
发表至: typescript
2022-02-24