泛型
泛型(Generics)允许在定义函数、类或接口时使用类型参数,从而使得这些函数、类或接口可以适用于多种不同的数据类型。泛型增强了代码的灵活性、可重用性和类型安全性。
函数的参数和返回值都是 any 类型,这意味着它可以接受任何类型的参数,并返回任何类型的值。虽然这种实现方式非常灵活,但缺乏类型安全性。
我们可以使用泛型来增加类型安全性,使得函数可以接受特定类型的参数,并返回相同类型的值。
普通函数
// 使用泛型改写函数,增加类型安全性
function identity<T>(arg: T): T {
return arg
}
// 使用泛型函数
let output = identity<string>('hello');
let output2 = identity<number>(1);
let output3 = identity<boolean>(false)
类
interface Item {
value: string;
}
class Child<T extends Item> {
private name: T;
constructor(value: T) {
this.name = value;
}
getName():T {
return this.name
}
}
class Parent extends Child<string> {
getName(): string {
return 'parent: ' + super.getName();
}
}
let stringParent = new Parent('hello')
stringParent.getName() // parent: hello
let numberChild = new Child<number>(2);
numberChild.getName() // 2