Sobes.tech
Junior — Middle

Explain the concept of Generics in TypeScript and how it is used to ensure type safety.

sobes.tech AI

Answer from AI

Generics in TypeScript allow creating components, functions, or classes that work with different data types while maintaining type safety.

This is achieved through type parameterization — instead of a specific type, a type parameter is used, which is specified during usage. As a result, the compiler checks the correctness of types, preventing errors.

Example:

function identity<T>(arg: T): T {
  return arg;
}

const num = identity<number>(42); // num has type number
const str = identity<string>("hello"); // str has type string

In this example, the identity function takes an argument of any type T and returns a value of the same type. This allows the function to be used with different types while maintaining strict typing.