【前端】【Ts】泛型详解
泛型是 TypeScript 中实现代码复用和增强灵活性的重要特性,允许在定义函数、接口或类时不预先指定具体类型,而是在使用时再确定。泛型函数、接口、类和约束共同构成 TypeScript 泛型系统,提供强大的类型复用和安全保障。使函数参数和返回值类型更灵活,定义时用类型参数代替具体类型,调用时确定类型,增强函数复用性。限制泛型类型必须满足某些条件,如具有特定属性或方法,确保在泛型代码中安全使用这
·
泛型 (Generics)
泛型是 TypeScript 中实现代码复用和增强灵活性的重要特性,允许在定义函数、接口或类时不预先指定具体类型,而是在使用时再确定。
(1) 泛型函数
概念
使函数参数和返回值类型更灵活,定义时用类型参数代替具体类型,调用时确定类型,增强函数复用性。
实用例子
// 定义泛型函数,交换数组中两个元素的位置
function swap<T>(arr: T[], index1: number, index2: number): T[] {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]];
return arr;
}
// 交换数字数组元素
const numArr = [1, 2, 3];
const swappedNumArr = swap(numArr, 0, 2);
console.log(swappedNumArr);
// 交换字符串数组元素
const strArr = ['a', 'b', 'c'];
const swappedStrArr = swap(strArr, 1, 2);
console.log(swappedStrArr);
(2) 泛型接口与类
泛型接口
- 概念:在接口定义中引入类型参数,使接口可用于不同数据类型,提高复用性。
- 实用例子
// 定义泛型接口表示存储数据的容器
interface Container<T> {
value: T;
getValue: () => T;
setValue: (newValue: T) => void;
}
// 实现泛型接口
const numberContainer: Container<number> = {
value: 10,
getValue() {
return this.value;
},
setValue(newValue) {
this.value = newValue;
}
};
console.log(numberContainer.getValue());
numberContainer.setValue(20);
console.log(numberContainer.getValue());
泛型类
- 概念:类定义中引入类型参数,类的属性和方法可使用该参数表示不同数据类型,提高类的复用性。
- 实用例子
// 定义泛型类表示栈
class Stack<T> {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
getSize() {
return this.items.length;
}
}
// 创建存储数字的栈
const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop());
// 创建存储字符串的栈
const stringStack = new Stack<string>();
stringStack.push('hello');
stringStack.push('world');
console.log(stringStack.pop());
(3) 泛型约束
概念
限制泛型类型必须满足某些条件,如具有特定属性或方法,确保在泛型代码中安全使用这些特性。
实用例子
// 定义接口要求类型具有 name 属性
interface HasName {
name: string;
}
// 定义泛型函数并使用泛型约束
function printName<T extends HasName>(obj: T) {
console.log(obj.name);
}
const person = { name: 'John', age: 30 };
printName(person);
// const num = 123;
// printName(num); // 报错,因为 number 类型没有 name 属性
泛型函数、接口、类和约束共同构成 TypeScript 泛型系统,提供强大的类型复用和安全保障。
更多推荐
所有评论(0)