深入理解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);