泛型
函数的泛型
单个泛型
function getVal<T>(val: T): T {
return val;
}
getVal<number>(1);
getVal<string>('1');
多个泛型
function getVal<T, P>(first: T, second: P) {
return `${first}${second}`;
}
getVal<string, number>('1', 2);
类的泛型
class Manager<T> {
constructor(private data: T[]) {}
getItem(index: number): T {
return this.data[index]
}
}
const data = new Manager<number>([1])
const data1 = new Manager<string>(['a'])
泛型约束
泛型通过extends实现泛型约束
interface Person {
name: string;
}
class Manager<T extends Person> {
constructor(private data: T[]) {}
getItem(index: number): string {
return this.data[index].name;
}
}
const data = new Manager([
{
name: 'tz',
},
]);