07Typescript中的综合使用

前面已经学习了 typescript 的相关概念、这里实现一个类型、接口、类 、泛型 综合使用的例子:
–TypeScript 封装统一操作 Mysql Mongodb Mssql 的底层类库

功能:定义一个操作数据库的库 支持 Mysql Mssql MongoDb

要求:Mysql MsSql MongoDb 功能一样 都有 add update delete get 方法

注意:约束统一的规范、以及代码重用

解决方案:需要约束规范所以要定义接口 ,需要代码重用所以用到泛型

    1、接口:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范

    2、泛型 通俗理解:泛型就是解决 类 接口 方法的复用性、
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// 1.定义一个接口
interface DBI<T> {
add(info: T): boolean;
update(info: T, id: number): boolean;
delete(id: number): boolean;
get(id: number): any[];
}

// 2.定义一个操作mysql数据库的类
// 注意:要实现泛型接口 这个类也应该是一个泛型类

class MySqlDb<T> implements DBI<T> {
constructor() {
console.log("数据库建立连接");
}
add(info: T): boolean {
console.log("mysql", info);
return true;
}
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[] {
var list = [
{
id: id,
title: "xxxx",
desc: "xxxxxxxxxx",
},
];
return list;
}
}

// 3.定义一个操作mssql数据库的类
class MsSqlDb<T> implements DBI<T> {
constructor() {
console.log("数据库建立连接");
}
add(info: T): boolean {
console.log("mssql", info);
return true;
}
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.");
}
}

// 4.定义一个操作mssql数据库的类
class MongoDb<T> implements DBI<T>{
constructor() {
console.log("数据库建立连接");
}
add(info: T): boolean {
console.log("mongoDb", info);
return true;
}
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.");
}

}

//5. 操作用户表 定义一个User类和数据表做映射

class User {
username: string | undefined;
password: string | undefined;
}

var u = new User();
u.username = "张三111";
u.password = "123456";

// 6. 调用
var oMySql = new MySqlDb<User>();
oMySql.add(u);
console.log(oMySql.get(1));

var oMsSql = new MsSqlDb<User>();
oMsSql.add(u);

var oMongoDb = new MongoDb<User>();
oMongoDb.add(u);

这里我们定义的所有类MySqlDb、MsSqlDb、MongoDb都要实现DBI的接口;同时类实例化之后传入的参数也需要遵守我们的泛型类User。