What are generics in TypeScript? Why are they useful?
Answer
Generics allow creating reusable components that work with a variety of types while maintaining type safety.
function identity<T>(arg: T): T {
return arg;
}
const numberIdentity = identity<number>(42); // Explicit type
const stringIdentity = identity("Hello"); // Type inferred
Why Useful:
Generics prevent duplication and allow functions or classes to operate on different types without losing type information.