TypeScript - Generics

Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type. So, components can be called or used with a variety of data types

class Queue<T> {
private data: T[] = [];
push(item: T) { this.data.push(item); }
pop(): T | undefined { return this.data.shift(); }
}

const queue = new Queue<number>();
queue.push(0);
queue.push("1"); // Error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
// And this Queue class can be reused for a string queue
const stringQueue = new Queue<string>();
stringQueue.push("1");
stringQueue.push(0); // Error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.