泛型
泛型允许在定义函数, 类或接口时, 使用类型参数来表示未指定的类型, 这些参数在具体使用时, 才被指定具体的类型, 泛型能让同一段代码适用于多种类型, 同时仍然保持类型的安全性
如下代码中<T>
就是泛型, 设置泛型后即可在函数中使用T
来表示该类型
泛型函数
ts
// 形参指定类型
function logData(data) { // 警告: 参数“data”隐式具有“any”类型
console.log(data)
}
function logData<T>(data: T) {
console.log(data)
}
logData<number>(100)
logData<string>('123')
泛型可以有多个
ts
// 多个泛型
function logInfo<T, U>(x: T, y: U): T | U {
console.log(x, y)
return Date.now() % 2 ? x : y
}
logInfo<number, string>(100, 'Halo')
logInfo<string, boolean>('Tom', false)
泛型接口
ts
interface PersonInterface<T, S> {
name: string,
age: number,
extraInfo: T,
ddrInfo: S
}
let manA: PersonInterface<string, boolean> = {
name: '张三',
age: 18,
extraInfo: 'Halo',
ddrInfo: false
}
type Job = {
title: string,
company: string
}
let manB: PersonInterface<Job, string> = {
name: '张三',
age: 18,
extraInfo: {
title: 'HHH',
company: 'atcat'
},
ddrInfo: '123'
}
泛型约束
ts
interface PersonInterface {
name: string,
age: number,
}
function logData<T extends PersonInterface>(info: T): void {
console.log(`我叫${info.name}, 今年${info.age}岁`)
}
logData({ name: '张三', age: 18 })
泛型类
ts
class Person<T> {
constructor(
public name: string,
public age: number,
public other: T
) {}
speak() {
console.log(`我叫${this.name}, 今年${this.age}岁`)
console.log(this.other)
}
}
const manA = new Person<number>('张三', 18, 250)
type Job = {
title: string,
company: string
}
const manB = new Person<Job>('李四', 10, {title: 'XXX', company: '哈哈哈'})