index.ts:

import {Users, UserModel} from './modle/user';
import {articalModel, ArticleCate} from './modle/article';

let users = new Users('lisile', '22222'); // Users { username: 'lisile', password: '22222' }
console.log(UserModel.add(users));

let articles = new ArticleCate('react', '框架', 123);
console.log(articalModel.add(articles)); // ArticleCate { title: 'react', desc: '框架', status: 123 }
1
2
3
4
5
6
7
8

user.ts

import {MysqlDB} from '../modules/db';

// 操作用户表,定义一个User类和数据表做映射
class Users {
    username:string | undefined;
    password:string | undefined;
    constructor(username:string | undefined, password:string | undefined) {
        this.username = username;
        this.password = password;
    }
}

let UserModel = new MysqlDB<Users>(); // Users类作为参数来约束数据传入的类型
export {
    UserModel,
    Users
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

artical.ts

import {MysqlDB} from '../modules/db';
class ArticleCate {
    title:string | undefined;
    desc:string | undefined;
    status: number | undefined;
    constructor(username:string | undefined, password:string | undefined, status: number | undefined) {
        this.title = username;
        this.desc = password;
        this.status = status;
    }
}

let articalModel = new MysqlDB<ArticleCate>();

export {
    ArticleCate,
    articalModel
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

db.ts

// 数据库接口
interface DB<T> {
    get(id:number):any[];
    add(info:T):boolean;
    update(info:T, id:number):boolean;
    delete(id:number):boolean;
}
// 定义一个操作mysql数据库的类
// 注意:要实现泛型接口,这个类也应该是一个泛型类
export class MysqlDB<T> implements DB<T> {
    constructor() {
        // 构造函数里实现与数据库建立连接
    }

    get(id: number): any[] {
        throw new Error("Method not implemented.");
    }
    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.");
    }
}

// 定义一个操作mssql数据库的类
export class MsSqlDB<T> implements DB<T> {
    get(id: number): any[] {
        throw new Error("Method not implemented.");
    }
    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.");
    }
}
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