Middle
What are generics and where have you actually used them?
sobes.tech AI
Answer from AI
Generics are a mechanism in programming languages (such as TypeScript, Java) that allows creating components that work with different data types while maintaining type safety.
In frontend development with TypeScript, I used generics to create versatile components and functions. For example, a generic function for working with arrays:
function getFirstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const firstNumber = getFirstElement<number>([1, 2, 3]);
const firstString = getFirstElement<string>(['a', 'b', 'c']);
I also used generics for typing React components so they could accept props with different data types, ensuring reusability and type safety.