Sobes.tech
Middle

What are generics in TypeScript and why are they needed?

sobes.tech AI

Answer from AI

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

Why are generics needed:

  • They enable writing reusable code without being tied to a specific type.
  • They provide type checking at compile time, reducing errors.

Example of using a generic in a function:

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

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

Here, T is a type parameter set when calling the function. This approach makes the code flexible and type-safe.