Sobes.tech
Middle

Can you explain what a generic is in TypeScript?

sobes.tech AI

Answer from AI

Generic in TypeScript is a way to create components, functions, or classes that work with different data types while maintaining type safety.

With generics, you can write universal code that is not tied to a specific type, but the compiler still checks for type correctness.

Example of a function with generics:

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

Here, T is a type parameter that is substituted when the function is called. This avoids the use of the any type and preserves type information, which improves autocomplete and prevents errors.