TypeScript Generics
What are Generics?
Generics let you write reusable code that works with different types.
Think of generics like a function parameter, but for types:
// Without generics - only works with strings
function firstString(arr: string[]): string {
return arr[0];
}
// With generics - works with any type
function first<T>(arr: T[]): T {
return arr[0];
}
// Usage
first<string>(["a", "b"]); // Returns string
first<number>([1, 2, 3]); // Returns number
Common Generic Patterns
Generic Functions
function identity<T>(value: T): T {
return value;
}
Generic Interfaces
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Usage
type WordResponse = ApiResponse<Word>;
type CategoryResponse = ApiResponse<Category>;
Generic Constraints
Limit what types can be used:
interface HasId {
id: string;
}
function findById<T extends HasId>(items: T[], id: string): T | undefined {
return items.find(item => item.id === id);
}
When to Use Generics
- Functions that work with multiple types
- Reusable data structures (like API responses)
- Utility types that transform other types
Key Takeaways
- Generics = type parameters
- Use
<T>to define a generic type - Constraints with
extendslimit valid types - Common in libraries and utility functions
TODO: Add more examples from VocabPal codebase