typescript类型 接口 类 泛类型的综合使用
dearweb
发布:2021-07-31 14:52:23阅读:
需要约束规范所以要定义接口,需要代码重用所以用到泛型接口 在面向对象的编程中接口是一种规范的定义,它定义了行为和动作的规范, 泛型 通俗理解:泛型就是解决类、接口的复用性。
interface DBI<T>{
add(info:T):boolean;
update(info:T,id:number):boolean;
delete(id:number):boolean;
get(id:number):any[];
}
// 定义一个操作Mysql的数据库的类 注意:要实现泛类型接口 这个类也应该是一个泛类型
class MysqlDb<T> implements DBI<T> {
add(info: T): boolean {
console.log(info)
return true
throw new Error("Method not implemented.")
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.")
}
delete(id: number): boolean {
throw new Error("Method not implemented.")
}
get(id: number): any[] {
throw new Error("Method not implemented.")
}
}
// 定义一个操作mssql的数据库的类
class MssqlDb<T> implements DBI<T> {
add(info: T): boolean {
throw new Error("Method not implemented.")
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.")
}
delete(id: number): boolean {
throw new Error("Method not implemented.")
}
get(id: number): any[] {
throw new Error("Method not implemented.")
}
}
// 操作用户表 定义一个user类和数据表做映射
class User {
username:string | undefined
password:string | undefined
}
let U = new User()
U.username = '李四'
U.password = '12345678'
let oMysql = new MysqlDb<User>();
oMysql.add(U) // {username: "李四", password: "12345678"}小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧