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

Generic Repository Pattern

Create a data access layer where entity types are parameterized for reusable CRUD operations.

Generic Repository Pattern

What you'll learn: How to build a flexible data access layer using generics so one set of CRUD methods can work with any entity type.


What Is the Generic Repository Pattern?

The repository pattern is a data access layer that sits between your application logic and your database. Instead of scattering database queries throughout your code, you centralize them in repository classes that handle Create, Read, Update, and Delete (CRUD) operations.

By making repositories generic, you write the CRUD logic once with a type parameter, then reuse it for every entity type (User, Product, Order, etc.) without duplicating code.


The Core Structure

A generic repository typically looks like this:

interface Entity {
  id: string;
}

class Repository<T extends Entity> {
  private items: T[] = [];

  findById(id: string): T | undefined {
    return this.items.find(item => item.id === id);
  }

  findAll(): T[] {
    return this.items;
  }

  create(item: T): T {
    this.items.push(item);
    return item;
  }

  update(id: string, updates: Partial<T>): T | undefined {
    const item = this.findById(id);
    if (item) {
      Object.assign(item, updates);
    }
    return item;
  }

  delete(id: string): boolean {
    const index = this.items.findIndex(item => item.id === id);
    if (index !== -1) {
      this.items.splice(index, 1);
      return true;
    }
    return false;
  }
}

Using It with Different Entities

interface User extends Entity {
  name: string;
  email: string;
}

interface Product extends Entity {
  title: string;
  price: number;
}

const userRepo = new Repository<User>();
const productRepo = new Repository<Product>();

userRepo.create({ id: "1", name: "Alice", email: "alice@example.com" });
productRepo.create({ id: "101", title: "Laptop", price: 999 });

const user = userRepo.findById("1"); // Typed as User | undefined

The constraint T extends Entity ensures every type has an id property, which the CRUD methods depend on. TypeScript infers the specific type at each call site, giving you full type safety without code duplication.


Key Takeaway: The generic repository pattern lets you parameterize entity types in a data access layer, writing CRUD operations once and reusing them type-safely across all your data models.