TypeScript接口,泛型练习

372 阅读1分钟

接口统一规范

泛型提高方法的复用性

// 定义接口
interface DBI<T> {
    add(info: T): boolean;
    update(info: T): boolean;
    delete(id: number): boolean;
    get(id: number): any[];
}


// 定义一个操作mysql数据库的类
// 要实现一个泛型接口, 这个类也应该是一个泛型类
class MySql<T> implements DBI<T> {
    // 可以接收实例化传过来的参数
    constructor(param) {
        console.log('连接成功' + param)
    }
    add(info: T): boolean {
        console.log('MySql', info);
        return true;
    }
    update(info: T): boolean {
        throw new Error("Method not implemented.");
    }
    delete(id: number): boolean {
        throw new Error("Method not implemented.");
    }
    get(id: number): any[] {
        var list = [
            { title: 'cccc1', desc: 'dsssfsf1' },
            { title: 'cccc2', desc: 'dsssfsf2' },
            { title: 'cccc3', desc: 'dsssfsf3' }
        ]
        return list;
    }

}

class Mysql2<T> implements DBI<T> {
    add(info: T): boolean {
        console.log('Mysql2', info);
        return true;
    }
    update(info: T): 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.");
    }
}


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

var u = new User();
u.username = 'zhangsan';
u.password = '52632';

//用类来约束传入数据的合法性
var mysql = new MySql<User>('哈哈');
console.log(mysql.add(u));// MySql User {username: "zhangsan", password: "52632"}
console.log(mysql.get(4)); // [{…}, {…}, {…}]
var mysql2 = new Mysql2<User>();
console.log(mysql2.add(u));//Mysql2 User {username: "zhangsan", password: "52632"}