Middle
What are generics in TypeScript?
sobes.tech AI
Answer from AI
Generics in TypeScript are a mechanism that allows creating components (functions, classes, interfaces) that work with different data types while maintaining type safety.
With generics, you can write a function or class that works with any type, with the type being determined at usage.
Example of a function with a generic:
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.
Generics increase code reusability and help create more versatile and type-safe APIs.