🎯 学习目标

  • 掌握泛型类的定义语法
  • 理解类中泛型的使用
  • 学会泛型约束在类中的应用
  • 了解泛型类的继承

📝 泛型类定义

// 泛型类 class Box<T> { private contents: T; constructor(initial: T) { this.contents = initial; } get(): T { return this.contents; } set(value: T): void { this.contents = value; } } const numberBox = new Box<number>(123); console.log(numberBox.get()); // 123 const stringBox = new Box('hello'); // 类型推断 console.log(stringBox.get()); // 'hello'

💻 实际应用

// 泛型栈 class Stack<T> { private items: T[] = []; push(item: T): void { this.items.push(item); } pop(): T | undefined { return this.items.pop(); } peek(): T | undefined { return this.items[this.items.length - 1]; } get size(): number { return this.items.length; } } const numberStack = new Stack<number>(); numberStack.push(1); numberStack.push(2); console.log(numberStack.pop()); // 2 // 泛型队列 class Queue<T> { private items: T[] = []; enqueue(item: T): void { this.items.push(item); } dequeue(): T | undefined { return this.items.shift(); } get isEmpty(): boolean { return this.items.length === 0; } }

📝 本节小结

  • • 类名后加 <T> 定义泛型类
  • • 泛型在类中所有成员可用
  • • 创建实例时指定具体类型
  • • 常用于集合、容器类