Q18: What are Generics and why are they important?
Generics allow you to write reusable, type-safe components that work across multiple data types rather than a single type, while preserving full static type safety.
Type parameters (conventionally written as <T>) act as type variables captured when functions, classes, or interfaces are invoked.
Generic Identity Function
function identity<T>(arg: T): T {
return arg;
}
const str = identity<string>("hello"); // Type: string
const num = identity(42); // Inferred automatically as number💡 Generics lock function input types to function output types dynamically.
Key Takeaways
- Generics provide type-safe reusability without resorting to
any. - TypeScript infers type parameters automatically based on argument values.