ts的泛型
// 泛型就是解决 类 接口的复用性 console.log('泛型泛型泛型泛型泛型.............') // T表示泛型 传入跟返回一致 function getData<T>(value: T): T { console.log(value) return value } getData<number>(123) // 类的泛型 class MinClass<T> { public list: T[] = [] add(value: T): void { this.list.push(value) } min(): T { console.log(this.list) return this.list[0] } } let m1 = new MinClass<number>() m1.add(1111) m1.add(222) m1.add(333) m1.min() let m2 = new MinClass<string>() m2.add('aaa') m2.add('bb') m2.add('cc') m2.min() // 泛型接口 interface ConfigFn { <T>(value: T): T } let setData: ConfigFn = function <T>(value: T): T { return value } console.log(setData<string>('name')) console.log(setData<number>(111212)) interface ConfigFn1<T> { (value: T): T } function setData1<T>(value: T): T { return value } let mySetData1: ConfigFn1<string> = setData1 console.log(mySetData1('name1')) // 把类作为参数来约束传入的数据 class User { username: string | undefined password: string | undefined } class ArticleCate { title: string | undefined desc: string | undefined status?: number = 12321 constructor(parmas: { title: string | undefined desc: string | undefined status?: number }) { this.title = parmas.title this.desc = parmas.desc this.status = parmas.status } } class MysqlDb<T> { add(log: T): boolean { console.log(log) return true } upData(log: T, id: number): boolean { console.log(log) console.log(id) return true } // 用泛型解决重复代码问题 // add1(user: User): boolean { // console.log(user) // return true // } // add2(info: ArticleCate): boolean { // console.log(info) // console.log(info.title) // return true // } } let u = new User() u.username = '张三' u.password = '123456' let art = new ArticleCate({ title: '张三', desc: '123456', }) let Db1 = new MysqlDb<User>() let Db2 = new MysqlDb<ArticleCate>() Db1.add(u) Db1.upData(u, 1) Db2.add(art) Db2.upData(art, 2)