Middle+
What are generics in TypeScript and what are they used for?
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.
They are used to write reusable code that is not tied to a specific type, but the compiler can still check for type correctness.
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 allows the function to work with any type, preserving information about the argument's type and the return value.