Generics
January 30, 2024Less than 1 minute
Generics
- A type parameter that we pass to another type
- Types that behave the same way, regardless of the type
- Using the type parameter makes sure that we always work with the same type (as input, output, modifications, ...)
Problem
- Let's say we have a
classQueue (first in, first out):
class Queue {
private data = [];
push(item) { this.data.push(item); }
pop() { return this.data.shift(); }
}
- In this case we can add anything (
string,number,object, ...) to the queue and when we pop it, it can be anything - This might be a problem if we need to perform some business logic inside our
Queue, like for example calculations (this won't work on non-numeric types)
Solution
- We can add a type parameter to the class, so when we use the class we already provide which type we are working with
class Queue<T> {
private data = [];
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 : cannot push a string. Only numbers allowed