Sobes.tech
Middle+

What is a generic in TypeScript?

sobes.tech AI

Answer from AI

Generic in TypeScript is a mechanism that allows creating components (functions, classes, interfaces) that work with different data types while maintaining type safety. Instead of a specific type, a type parameter is specified, which is set during usage. This enables writing more versatile and reusable code.

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

Here, T is a type parameter that is substituted during the function call.