Skip to main content

Lesson 6 of 8

Dependency Injection in TypeScript

Dependency Injection (DI) is a pattern where a class receives its dependencies through the constructor rather than creating them internally. TypeScript's type system makes DI clean - you inject interfaces, not implementations. This makes code testable, swappable, and decoupled.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Manual DI - Constructor Injection Pattern

Manual DI - Constructor Injection Pattern
// ── Without DI - tightly coupled, hard to test ───────────────
class BadTaskService {
  private repo = new PgTaskRepository(new Database());  // hardcoded!
  private emailer = new EmailNotifier(new MailService()); // hardcoded!
  // Impossible to unit test without a real database
}

// ── With DI - loosely coupled, fully testable ─────────────────
// Interfaces (contracts)
interface TaskRepository { findById(id: number): Promise<Task | null>; save(t: Task): Promise<Task>; }
interface Notifier        { notify(userId: number, msg: string): Promise<void>; }
interface Logger          { info(msg: string, ctx?: object): void; error(msg: string, err?: Error): void; }

class TaskService {
  constructor(
    private readonly repo:     TaskRepository,
    private readonly notifier: Notifier,
    private readonly logger:   Logger,
  ) {}

  async completeTask(taskId: number, userId: number): Promise<Task> {
    const task = await this.repo.findById(taskId);
    if (!task) throw new Error(`Task ${taskId} not found`);

    const completed = await this.repo.save({
      ...task,
      status: "done",
      updatedAt: new Date(),
    });

    await this.notifier.notify(userId, `Task "${task.title}" completed!`);
    this.logger.info("Task completed", { taskId, userId });

    return completed;
  }
}

// ── Production: real implementations ─────────────────────────
const prodService = new TaskService(
  new PgTaskRepository(db),
  new EmailNotifier(mailer),
  new MonologLogger(),
);

// ── Test: fake/mock implementations ───────────────────────────
class MockNotifier implements Notifier {
  public readonly sent: Array<{ userId: number; msg: string }> = [];
  async notify(userId: number, msg: string): Promise<void> {
    this.sent.push({ userId, msg });
  }
}
class ConsoleLogger implements Logger {
  info(msg: string) { /* silent in tests */ }
  error(msg: string) { /* silent in tests */ }
}

const mockNotifier = new MockNotifier();
const testService  = new TaskService(
  new InMemoryTaskRepository(),
  mockNotifier,
  new ConsoleLogger(),
);

// ── Simple DI container (manual factory) ─────────────────────
class Container {
  private static readonly singletons = new Map<string, unknown>();

  static register<T>(key: string, factory: () => T): void {
    // Lazy singleton - created on first request
    if (!this.singletons.has(key)) {
      this.singletons.set(key, factory());
    }
  }

  static resolve<T>(key: string): T {
    const instance = this.singletons.get(key);
    if (!instance) throw new Error(`Dependency "${key}" not registered`);
    return instance as T;
  }
}

Container.register("taskRepo",    () => new PgTaskRepository(db));
Container.register("notifier",    () => new EmailNotifier(mailer));
Container.register("logger",      () => new MonologLogger());
Container.register("taskService", () => new TaskService(
  Container.resolve("taskRepo"),
  Container.resolve("notifier"),
  Container.resolve("logger"),
));

Common Mistakes

  • Creating dependencies inside the class (`new X()`) - this hardcodes the implementation and makes the class impossible to test in isolation. Always receive dependencies through the constructor.
  • Injecting concrete classes instead of interfaces - `constructor(private repo: PgTaskRepository)` forces production DB usage everywhere. Inject the interface `TaskRepository` instead.
  • Building a complex DI container from scratch in small projects - for simple apps, constructor injection without a container is fine. Only add a container (or use inversify/tsyringe) when the dependency graph becomes complex.

Tip

Tip

Practice Dependency Injection in TypeScript 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 Dependency Injection in TypeScript

Practice Task

Note

Practice Task - (1) Write a working example of Dependency Injection in TypeScript 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 Dependency Injection in TypeScript 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

  • Dependency Injection (DI) is a pattern where a class receives its dependencies through the constructor rather than creating them internally.
  • Creating dependencies inside the class (`new X()`) - this hardcodes the implementation and makes the class impossible to test in isolation. Always receive dependencies through the constructor.
  • Injecting concrete classes instead of interfaces - `constructor(private repo: PgTaskRepository)` forces production DB usage everywhere. Inject the interface `TaskRepository` instead.
  • Building a complex DI container from scratch in small projects - for simple apps, constructor injection without a container is fine. Only add a container (or use inversify/tsyringe) when the dependency graph becomes complex.

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