第6章:泛型
泛型类
基本概念
泛型类(Generic Class)是 TypeScript 中实现类型参数化的类,允许在类定义时使用类型变量,并在实例化时指定具体类型。泛型类通过<T>语法声明类型参数,可应用于类的属性、方法或构造函数中。
class Box<T> {
private content: T;
constructor(value: T) {
this.content = value;
}
getValue(): T {
return this.content;
}
}
// 实例化时指定具体类型
const numberBox = new Box<number>(42);
const stringBox = new Box<string>("Hello");
核心特性
多类型参数支持
类可声明多个类型参数,用逗号分隔:class Pair<K, V> { constructor(public key: K, public value: V) {} }类型参数默认值
TypeScript 4.0+ 支持为泛型参数提供默认类型:class Container<T = string> { constructor(public item: T) {} }约束泛型类型
通过extends关键字限制类型参数的范围:class Logger<T extends { toString(): string }> { log(item: T) { console.log(item.toString()); } }
典型应用场景
集合类实现
class Stack<T> { private items: T[] = []; push(item: T) { this.items.push(item); } pop(): T | undefined { return this.items.pop(); } }响应式编程中的Wrapper类
class Observable<T> { constructor(private value: T) {} subscribe(callback: (val: T) => void) { /*...*/ } }工厂模式
class Creator<T> { create(ctor: new () => T): T { return new ctor(); } }
注意事项
静态成员不能使用泛型类型
静态成员属于类本身而非实例,无法访问类的类型参数:class Example<T> { static defaultValue: T; // ❌ 错误 }类型擦除机制
泛型类型信息仅在编译阶段存在,运行时会被替换为实际类型或Object。继承泛型类
子类可继承父类的类型参数或指定具体类型:class Child<T> extends Parent<T> {} // 保持泛型 class StringChild extends Parent<string> {} // 具体化
示例:泛型缓存系统
class Cache<T> {
private data: Map<string, T> = new Map();
set(key: string, value: T): void {
this.data.set(key, value);
}
get(key: string): T | undefined {
return this.data.get(key);
}
}
// 使用示例
const userCache = new Cache<{name: string, age: number}>();
userCache.set("user1", {name: "Alice", age: 30});
最佳实践:当类的行为需要适用于多种数据类型,且类型关系需要明确约束时,优先考虑使用泛型类。避免过度使用导致类型系统复杂化。
