Medium Programming & OOP JavaScript & TypeScript
What are generics in TypeScript and how are they used?
Answer
Generics enable type-safe reusable components that work with different types. Syntax: function identity<T>(arg: T): T { return arg; }. Type parameter <T> is placeholder for actual type. Use cases: type-safe containers/collections, utility types, factory functions. Constraints: <T extends SomeType> limits acceptable types. Multiple parameters: <K, V>. Default types: <T = string>. Generic classes, interfaces supported. Built-in: Array<T>, Promise<T>, Map<K,V>. Benefits: type safety without sacrificing flexibility, better IDE support, catch errors at compile time.
IIT Certified
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.
Relevant for Roles
TypeScript Developer Frontend Developer Full Stack Developer