深入理解typeScript中的泛型类

 类当做参数的泛型类  (把类当做参数来约束数据传入的类型)

class MysqlDb<T>{
    add(info:T):boolean{
        console.log(info);
        return true;
    }
}

class User{
    userName: string | undefined;
    passWord: string | undefined;
}

var u = new User();
u.userName = '张三';
u.passWord = '123456'
// 类当做参数的泛型类
var users = new MysqlDb<User>();
users.add(u);

class Book{
    name:string | undefined;
    price: number | undefined;
    surplus: number | undefined;

    constructor(params:{
        name:string | undefined;
        price: number | undefined;
        surplus?: number | undefined;
    }){
        this.name = params.name;
        this.price = params.price;
        this.surplus = params.surplus;
    }
}

var storyBook = new Book({
    name : '格林童话',
    price : 36,
    surplus : 377
});

var books = new MysqlDb<Book>();
books.add(storyBook);

posted @ 2020-04-14 10:36  砂糖一椰子  阅读(1260)  评论(0编辑  收藏  举报