Junior — Middle
What is the role of generics in programming?
sobes.tech AI
Answer from AI
Generic types (Generics) allow creating components (functions, classes) that work with different data types while maintaining type safety. This means you can write code that is universal and reusable, but the compiler will still check for type correctness.
For example, in TypeScript (often used with Node.js), you can declare a generic class:
class Box<T> {
private content: T;
constructor(value: T) {
this.content = value;
}
getContent(): T {
return this.content;
}
}
const numberBox = new Box<number>(123);
console.log(numberBox.getContent()); // 123
const stringBox = new Box<string>('text');
console.log(stringBox.getContent()); // text
Here, T is a type parameter that is replaced with a specific type when creating an instance. This avoids the use of any and errors related to incorrect types.
Thus, Generics increase the flexibility and safety of the code.