Common Generic Interface Patterns
What you'll learn: How generic interfaces appear in real-world TypeScript codebases as recurring, recognizable shapes.
The Reality of Generic Interfaces
While you can create custom generic interfaces for any purpose, the TypeScript community has converged on several standard patterns that appear again and again. Recognizing these shapes helps you read library code, design consistent APIs, and communicate intent clearly.
Three Classic Patterns
Result<T>
Represents an operation that might succeed or fail:
interface Result<T> {
success: boolean;
value?: T;
error?: string;
}
// Usage
function parseNumber(input: string): Result<number> {
const num = parseFloat(input);
if (isNaN(num)) {
return { success: false, error: "Invalid number" };
}
return { success: true, value: num };
}
Container<T>
Wraps a value with metadata or behavior:
interface Container<T> {
data: T;
timestamp: number;
isLoaded: boolean;
}
// Usage
const userContainer: Container<{ name: string }> = {
data: { name: "Alice" },
timestamp: Date.now(),
isLoaded: true
};
Repository<T>
Abstracts data access operations:
interface Repository<T> {
getById(id: string): T | undefined;
getAll(): T[];
save(item: T): void;
delete(id: string): boolean;
}
Why These Patterns Matter
These interfaces are templates for common problems. A Result handles error states, a Container adds context to values, and a Repository standardizes data operations. You'll see variations of these everywhere—in Redux state, HTTP clients, database layers, and more.
Key Takeaway: Real-world code reuses generic interface patterns like Result<T>, Container<T>, and Repository<T> to solve recurring problems with consistent, type-safe shapes.