Sobes.tech
Middle+

Have you worked with generics? Can you explain the general concept?

sobes.tech AI

Answer from AI

Generics are a mechanism that allows creating components, functions, or classes that work with different data types while maintaining type safety. Instead of writing separate code for each type, you can write a universal template.

For example, in TypeScript, you can write a function that returns an element of any array type:

function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

const num = firstElement([1, 2, 3]); // number
const str = firstElement(['a', 'b']); // string

Here, <T> is a type parameter that is substituted when the function is called. This increases code reusability and reduces errors related to incorrect types.