Sobes.tech
Junior — Middle

Can you explain the concept of generic types or templates in programming?

sobes.tech AI

Answer from AI

Generic types or templates allow you to write functions, classes, or interfaces that work with different data types while maintaining type safety. This means you can create universal components without duplicating code for each specific type.

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

function getFirstElement<T>(arr: T[]): T {
  return arr[0];
}

const num = getFirstElement([1, 2, 3]); // type number
const str = getFirstElement(["a", "b"]); // type string

Here, <T> is a type parameter that is substituted when the function is called. This increases flexibility and reusability of the code, and also helps avoid type errors.