Generics
The Cache That Almost Crashed Our Database
// cache.js - Our old JavaScript cache
class Cache {
constructor() {
this.data = new Map();
}
get(key) {
return this.data.get(key); // What type is this?
}
set(key, value) {
this.data.set(key, value); // What type is value?
}
}
// Usage
const userCache = new Cache();
userCache.set('user-123', { id: '123', name: 'John' });
const user = userCache.get('user-123');
console.log(user.name); // Works
// But then someone did this:
const productCache = new Cache();
productCache.set('prod-456', '{"id":"456","name":"Laptop"}'); // String instead of object!
const product = productCache.get('prod-456');
console.log(product.price); // Undefined! Should have been parsed firstGeneric Functions
Basic Generic Function
Generic Array Functions
Multiple Type Parameters
Real-World Example: API Wrapper
Generic Constraints
extends Constraint
Constraining to Object Types
Multiple Constraints
Generic Interfaces
Basic Generic Interface
Generic Interface with Multiple Parameters
Real-World Example: Repository Pattern
Generic Classes
Basic Generic Class
Generic Class with Constraints
Real-World Example: Event Emitter
Default Type Parameters
Basic Default Type
Default with Constraints
Generic Utility Functions
Map Function
Filter Function
Reduce Function
Advanced Generic Patterns
Generic Factory Function
Generic Mixin Pattern
Conditional Types with Generics
Real-World Example: Type-Safe State Management
Common Mistakes I Made
1. Not Using Generic Constraints
2. Over-Complicating with Generics
3. Forgetting Generic Constraints
Your Challenge
Key Takeaways
What I Learned
PreviousAdvanced Types - Unions, Intersections, and Type GuardsNextType Manipulation & Utility Types
Last updated