Middle+
Did you use generics in TypeScript? Explain their purpose and give an example.
sobes.tech AI
Answer from AI
Yes, I used generics in TypeScript to create versatile components and functions that work with different data types while maintaining type safety.
For example, you can write a function that returns the first element of an array of any type:
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
const num = firstElement([1, 2, 3]); // type number
const str = firstElement(['a', 'b']); // type string
Here, <T> is a type parameter that allows the function to be generic. This helps avoid code duplication and type errors.