Sobes.tech
Middle

What are generics in TypeScript?

sobes.tech AI

Answer from AI

Generics in TypeScript are a mechanism that allows creating 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 knows which type it is working with.

Example of a generic function:

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 information about the argument and return types.

Generics are widely used in collections, for example, in arrays or interfaces to describe data structures with parameterized types.

What are generics in TypeScript? — Frontend - sobes.tech