Using the same code with different types and using generics

When we first start developing classes in TypeScript, it is very common for us to repeat the same code again and again, only changing the type that we are relying on. For instance, if we wanted to store a queue of integers, we might be tempted to write the following class:

class QueueOfInt {    private queue : number[]= [];    public Push(value : number) : void {        this.queue.push(value);    }    public Pop() : number | undefined {        return this.queue.shift();    }}

Calling this code is as easy as this:

const intQueue : QueueOfInt = new QueueOfInt();intQueue.Push(10);intQueue.Push(35);console.log(intQueue.Pop()); // Prints 10console.log(intQueue.Pop()); // Prints 35

Later on, we decide that we also ...

Get Advanced TypeScript Programming Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.