Course contentsShow
← TypeScript
Lesson 614 of 1,79614. Generics in PracticeFree lesson

Generic Repository Pattern

Type data access layers with generic CRUD operations that work across entity types.

Generic Repository Pattern

What you'll learn: How to build a reusable data access layer using generics to handle CRUD operations for any entity type.

The Core Problem

Imagine you're building an app with Users, Products, and Orders. Without generics, you'd write three nearly identical repository classes—each with findById(), save(), delete(), etc. Copy-paste code everywhere. The Generic Repository Pattern solves this by creating one repository type that adapts to any entity shape.

How It Works

A generic repository is a class or interface parameterized by the entity type T. It defines standard CRUD operations (Create, Read, Update, Delete) that work universally. Each method uses T to ensure type safety for that specific entity.

interface Repository<T> {
  findById(id: string): T | undefined;
  findAll(): T[];
  save(entity: T): void;
  delete(id: string): void;
}

Now you can create concrete repositories:

type User = { id: string; name: string };
type Product = { id: string; price: number };

const userRepo: Repository<User> = {
  findById(id) { /* ... */ return undefined; },
  findAll() { return []; },
  save(user) { /* user is typed as User */ },
  delete(id) { /* ... */ }
};

const productRepo: Repository<Product> = {
  /* same structure, different entity type */
  findById(id) { return undefined; },
  findAll() { return []; },
  save(product) { /* product is typed as Product */ },
  delete(id) { /* ... */ }
};

TypeScript ensures userRepo.save() only accepts User objects, while productRepo.save() only accepts Product objects—all from one generic definition.

Key Takeaway: The Generic Repository Pattern uses type parameters to create a single, reusable data access layer that enforces type safety across all entity types, eliminating duplication and errors.