泛型:解决 类、接口、方法的复用性、以及对不特定数据类型的支持
传入的参数与返回参数类型一致
泛型函数
// T表示泛型,具体什么类型是调用这个方法的时候决定的
function getData<T>(value: T): T {return value
}
getData<number>(123) //参数必须是number
getData<string>('123')
泛型类
//支持返回数字和字符串两种类型,通过类的泛型实现
class MinClass<T> {public list: T[] = [];add(num: T) {this.list.push(num)}min(): T {var minNum = this.list[0];for (let i = 0; i < this.list.length; i++) {if (minNum > this.list[i]) {minNum = this.list[i]}}return minNum}
}
var m = new MinClass<number>() // 实例化类,并且指定了类的T代表的类型是number
m.add(2)
m.add(5)
m.add(10)
console.log(m.min());
把类当作参数来约束数据传入的类型
class User {username: string | undefined;password: string | undefined
}
class MysqlDb {add(user: User): boolean {console.log(user, 'user');return true}
}
var u = new User()
u.username = 'w'
u.password = '1'var Db = new MysqlDb()
Db.add(u)// 操作泛型类
class TMysqlDb<T> {add(info: T): boolean {console.log(info, 'info');return true}
}
// 给user添加数据
// 定义一个TUser类,进行映射
class TUser {username: string | undefined;password: string | undefined
}
var t = new TUser()
t.username = 't'
t.password = '6'var tb = new TMysqlDb<TUser>()
tb.add(t)class ArticleCate {title: string | undefined;desc: string | undefined;status: number | undefinedconstructor(params: {title: string | undefined,desc: string | undefined,status: number | undefined}) {this.title = params.titlethis.desc = params.descthis.status = params.status}
}
var a = new ArticleCate({ title: '分类', desc: '描述', status: 0 })
var td = new TMysqlDb<ArticleCate>()
td.add(a)
泛型接口
// 方法1
interface ConfigFn {<T>(value: T): T
}
var getData: ConfigFn = function <T>(value: T): T {return value
}
console.log(getData<string>('name'));// 方法2
interface ConfigFn<T> {(value: T): T
}
function getData<T>(value: T): T {return value
}
var myGetData: ConfigFn<string> = getData
console.log(myGetData('20'));