摘要:在本教程中,您将学习如何开发 TypeScript 泛型类。
TypeScript 泛型类的介绍
一个 泛型 类在类名后面有尖括号 <>
中的泛型类型参数列表
class className<T>{
//...
}
Code language: TypeScript (typescript)
TypeScript 允许您在类型参数列表中拥有多个泛型类型。例如
class className<K,T>{
//...
}
Code language: TypeScript (typescript)
泛型约束也应用于类中的泛型类型
class className<T extends TypeA>{
//...
}
Code language: TypeScript (typescript)
将类型参数放在类上允许您开发使用相同类型的方法和属性。
TypeScript 泛型类示例
在此示例中,我们将开发一个泛型 Stack
类。
堆栈是一种数据结构,它基于后进先出 (LIFO) 原则。这意味着您放入堆栈中的第一个元素是您从堆栈中获得的最后一个元素。
通常,堆栈有一个大小。默认情况下,它是空的。堆栈有两个主要操作
- 推送:将元素推入堆栈。
- 弹出:从堆栈中弹出元素。
以下显示了一个完整的泛型 Stack 类,称为 Stack<T>
class Stack<T> {
private elements: T[] = [];
constructor(private size: number) {
}
isEmpty(): boolean {
return this.elements.length === 0;
}
isFull(): boolean {
return this.elements.length === this.size;
}
push(element: T): void {
if (this.elements.length === this.size) {
throw new Error('The stack is overflow!');
}
this.elements.push(element);
}
pop(): T {
if (this.elements.length == 0) {
throw new Error('The stack is empty!');
}
return this.elements.pop();
}
}
Code language: TypeScript (typescript)
以下创建了一个新的数字堆栈
let numbers = new Stack<number>(5);
Code language: TypeScript (typescript)
此函数返回两个数字 low
和 high
之间的随机数
function randBetween(low: number, high: number): number {
return Math.floor(Math.random() * (high - low + 1) + low);
}
Code language: TypeScript (typescript)
现在,您可以使用 randBetween()
函数为推入 numbers
堆栈生成随机数
let numbers = new Stack<number>(5);
while (!numbers.isFull()) {
let n = randBetween(1, 10);
console.log(`Push ${n} into the stack.`)
numbers.push(n);
}
Code language: TypeScript (typescript)
输出
Push 3 into the stack.
Push 2 into the stack.
Push 1 into the stack.
Push 8 into the stack.
Push 9 into the stack.
Code language: TypeScript (typescript)
以下显示了如何从堆栈中弹出元素,直到它为空
while (!numbers.isEmpty()) {
let n = numbers.pop();
console.log(`Pop ${n} from the stack.`);
}
Code language: TypeScript (typescript)
输出
Pop 9 from the stack.
Pop 8 from the stack.
Pop 1 from the stack.
Pop 2 from the stack.
Pop 3 from the stack.
Code language: TypeScript (typescript)
类似地,您可以创建一个字符串堆栈。例如
let words = 'The quick brown fox jumps over the lazy dog'.split(' ');
let wordStack = new Stack<string>(words.length);
// push words into the stack
words.forEach(word => wordStack.push(word));
// pop words from the stack
while (!wordStack.isEmpty()) {
console.log(wordStack.pop());
}
Code language: TypeScript (typescript)
它是如何工作的
- 首先,将句子拆分为单词。
- 其次,创建一个大小等于
words
数组中单词数量的堆栈。 - 第三,将
words
数组的元素推入堆栈。 - 最后,从堆栈中弹出单词,直到它为空。
在本教程中,您学习了如何在 TypeScript 中开发泛型类。
本教程是否有帮助?