title: 泛型类

泛型类

原文地址

在本教程中,你将学习开发 TypeScript 中的泛型类。

TypeScript 中的泛型类介绍

泛型 类的语法如下,泛型类型参数列表在尖括号 <> 中,类名之后:

  1. class className<T> {
  2. //...
  3. }

TypeScript 允许类型参数列表中存在多个泛型类型,如下所示:

  1. class className<K, T> {
  2. //...
  3. }

泛型约束 同样可以应用于类中的泛型类型:

  1. class className<T extends TypeA> {
  2. //...
  3. }

在类上放置类型参数允许你开发相同类型的方法和属性。

泛型类例子

在这个例子中,我们将开发一个 Stack 泛型类。

栈是一个基于后进先出 (LIFO) 原则的数据结构,这意味着第一个放入到栈中的元素会是栈中最后一个获取到的元素。

通常栈有大小的限制,默认为空,栈有两个主要的操作:

  • Push: 将一个元素推入到栈中
  • Pop: 从栈中弹出一个元素

下面演示一个完整的栈泛型类代码,名为 Stack<T>

  1. class Stack<T> {
  2. private elements: T[] = [];
  3. constructor(private size: number) {}
  4. isEmpty(): boolean {
  5. return this.elements.length === 0;
  6. }
  7. isFull(): boolean {
  8. return this.elements.length === this.size;
  9. }
  10. push(element: T): void {
  11. if (this.elements.length === this.size) {
  12. throw new Error('The stack is overflow!');
  13. }
  14. this.elements.push(element);
  15. }
  16. pop(): T {
  17. if (this.elements.length == 0) {
  18. throw new Error('The stack is empty!');
  19. }
  20. return this.elements.pop();
  21. }
  22. }

下面创建了一个数字栈:

  1. let numbers = new Stack<number>(5);

下面的函数返回 lowhigh 两个数字之间的随机数:

  1. function randBetween(low: number, high: number): number {
  2. return Math.floor(Math.random() * (high - low + 1) + low);
  3. }

现在可以使用 randBetween() 函数生成随机数,然后推入到数字栈中:

  1. let numbers = new Stack<number>(5);
  2. while (!numbers.isFull()) {
  3. let n = randBetween(1, 10);
  4. console.log(`Push ${n} into the stack.`);
  5. numbers.push(n);
  6. }

输出:

  1. Push 3 into the stack.
  2. Push 2 into the stack.
  3. Push 1 into the stack.
  4. Push 8 into the stack.
  5. Push 9 into the stack.

下面演示从栈中弹出元素的操作,直到栈为空:

  1. while (!numbers.isEmpty()) {
  2. let n = numbers.pop();
  3. console.log(`Pop ${n} from the stack.`);
  4. }

输出:

  1. Pop 9 from the stack.
  2. Pop 8 from the stack.
  3. Pop 1 from the stack.
  4. Pop 2 from the stack.
  5. Pop 3 from the stack.

同样的,你可以创建一个字符串栈,如下所示:

  1. let words = 'The quick brown fox jumps over the lazy dog'.split(' ');
  2. let wordStack = new Stack<string>(words.length);
  3. // push words into the stack
  4. words.forEach((word) => wordStack.push(word));
  5. // pop words from the stack
  6. while (!wordStack.isEmpty()) {
  7. console.log(wordStack.pop());
  8. }

它是这样工作的:

  • 首先,把句子拆分成单词;
  • 然后,创建一个栈,大小等于单词数组的单词数量;
  • 第三,将单词数组中的单词逐个推入到栈中;
  • 最后,将栈中的单词弹出,直到栈为空。