TypeScript高级特性全解析
1. 泛型的使用
1.1 重复代码问题
在TypeScript开发类时,我们常常会重复编写相同的代码,只是依赖的类型不同。例如,我们分别创建整数队列和字符串队列时,代码如下:
class QueueOfInt {
private queue : number[]= [];
public Push(value : number) : void {
this.queue.push(value);
}
public Pop() : number | undefined {
return this.queue.shift();
}
}
const intQueue : QueueOfInt = new QueueOfInt();
intQueue.Push(10);
intQueue.Push(35);
console.log(intQueue.Pop());
console.log(intQueue.Pop());
class QueueOfString {
private queue : string[]= [];
public Push(value : string) : void {
this.queue.push(value);
}
public Pop() : string | undefined {
return this.queue.shift();
}
}
这种方式不仅代码冗
超级会员免费看
订阅专栏 解锁全文
796

被折叠的 条评论
为什么被折叠?



