TypeScript Generics
🧬 TypeScript Generics
📌 Think of generics as placeholders for types
1️⃣ Why Generics?
Without generics, you lose type safety:
With generics ✅:
2️⃣ Generic Functions
✔ Type-safe
✔ Reusable
3️⃣ Type Inference with Generics
You usually don’t need to specify the type.
4️⃣ Generic Arrow Functions
5️⃣ Generic Interfaces
6️⃣ Generic Classes
7️⃣ Multiple Generic Types
8️⃣ Generic Constraints (extends)
Restrict the types that can be used.
❌ Error:
9️⃣ keyof with Generics
🔟 Generic Default Types
🔑 Generics Summary
| Feature | Example |
|---|---|
| Function | <T>(value: T) |
| Class | class Box<T> |
| Interface | interface Api<T> |
| Multiple | <K, V> |
| Constraint | extends |
| keyof | K extends keyof T |
⭐ Best Practices
✔ Use generics to avoid any
✔ Keep generic names short (T, K, V)
✔ Add constraints for safety
✔ Don’t over-complicate generics
