Middle
What are generic types in TypeScript? Why use them? Are they a good practice or an anti-pattern?
sobes.tech AI
Answer from AI
Generic types in TypeScript allow creating components and functions that work with different data types while maintaining type safety. These are type templates that are parameterized when used.
Why use:
- They increase code reusability.
- They allow writing more abstract and universal functions/classes.
- They preserve type information, which helps avoid errors.
This is good practice if generics are used consciously and without complicating the code unnecessarily. They help make the code more flexible and safe, unlike using the 'any' type, which disables type checking.
Example:
function identity<T>(arg: T): T {
return arg;
}
const num = identity<number>(42);
const str = identity<string>("hello");
Here, the identity function returns an argument of the same type it receives, thanks to the generic T.