Skip to main content

Lesson 3 of 8

Interfaces & Class Implementation

When a class `implements` an interface, TypeScript verifies the class satisfies the interface's contract. This is the foundation of Dependency Injection and testability - callers depend on the interface, not the concrete class. You can swap implementations (real vs mock) without changing callers.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Interfaces, Implementation & Dependency Inversion

Interfaces, Implementation & Dependency Inversion
// ── Interface defines the contract ───────────────────────────
interface TaskRepository {
  findById(id: number): Promise<Task | null>;
  findAll(options?: { status?: TaskStatus; limit?: number }): Promise<Task[]>;
  save(task: Task): Promise<Task>;
  delete(id: number): Promise<void>;
}

// ── Concrete implementation - real database ────────────────────
class PgTaskRepository implements TaskRepository {
  constructor(private readonly db: Database) {}

  async findById(id: number): Promise<Task | null> {
    const row = await this.db.query(
      "SELECT * FROM tasks WHERE id = $1", [id]
    );
    return row ?? null;
  }

  async findAll({ status, limit = 50 } = {}): Promise<Task[]> {
    const q = status
      ? "SELECT * FROM tasks WHERE status = $1 LIMIT $2"
      : "SELECT * FROM tasks LIMIT $1";
    return this.db.queryAll(status ? [status, limit] : [limit]);
  }

  async save(task: Task): Promise<Task> {
    await this.db.upsert("tasks", task);
    return task;
  }

  async delete(id: number): Promise<void> {
    await this.db.execute("DELETE FROM tasks WHERE id = $1", [id]);
  }
}

// ── Test double - in-memory implementation ────────────────────
class InMemoryTaskRepository implements TaskRepository {
  private tasks = new Map<number, Task>();

  async findById(id: number): Promise<Task | null> {
    return this.tasks.get(id) ?? null;
  }

  async findAll({ status }: { status?: TaskStatus } = {}): Promise<Task[]> {
    const all = [...this.tasks.values()];
    return status ? all.filter((t) => t.status === status) : all;
  }

  async save(task: Task): Promise<Task> {
    this.tasks.set(task.id, task);
    return task;
  }

  async delete(id: number): Promise<void> {
    this.tasks.delete(id);
  }
}

// ── Service depends on the INTERFACE, not the class ───────────
class TaskService {
  constructor(private readonly repo: TaskRepository) {}
  // Works with PgTaskRepository in production, InMemoryTaskRepository in tests

  async completeTask(id: number): Promise<Task> {
    const task = await this.repo.findById(id);
    if (!task) throw new Error(`Task ${id} not found`);
    return this.repo.save({ ...task, status: "done", updatedAt: new Date() });
  }
}

// ── Usage: swap without changing TaskService ──────────────────
const prodService = new TaskService(new PgTaskRepository(db));
const testService = new TaskService(new InMemoryTaskRepository()); // ✅

Common Mistakes

  • Depending on concrete classes instead of interfaces - `constructor(private repo: PgTaskRepository)` makes the service impossible to test without a real DB. Always depend on the interface.
  • Putting implementation details in the interface - `TaskRepository` should not have `db: Database` or `connectionString: string`. Keep interfaces clean contracts with no implementation details.
  • One interface per class - interfaces should be named by what they provide, not by the class that implements them. `TaskRepository` is better than `ITaskRepository`. The `I` prefix is a Java/C# convention TypeScript doesn't need.

Tip

Tip

Practice Interfaces Class Implementation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Interfaces & Class Implementation

Practice Task

Note

Practice Task - (1) Write a working example of Interfaces Class Implementation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Interfaces Class Implementation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • When a class `implements` an interface, TypeScript verifies the class satisfies the interface's contract.
  • Depending on concrete classes instead of interfaces - `constructor(private repo: PgTaskRepository)` makes the service impossible to test without a real DB. Always depend on the interface.
  • Putting implementation details in the interface - `TaskRepository` should not have `db: Database` or `connectionString: string`. Keep interfaces clean contracts with no implementation details.
  • One interface per class - interfaces should be named by what they provide, not by the class that implements them. `TaskRepository` is better than `ITaskRepository`. The `I` prefix is a Java/C# convention TypeScript doesn't need.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done