January 19, 2026 (10mo ago) — last updated November 15, 2026 (3d ago)

TypeScript Singleton Pattern: Complete Guide

Learn the TypeScript Singleton pattern: implementation, trade-offs, testing strategies, DI alternatives, and step-by-step refactor guidance.

← Back to blog
Cover Image for TypeScript Singleton Pattern: Complete Guide

Learn the TypeScript Singleton pattern: what it is, when to use it, how to implement it safely, and practical alternatives like dependency injection to improve testability and maintainability.

TypeScript Singleton Pattern: Complete Guide

A pencil sketch of a regal scribe wearing a crown, diligently examining a glowing scroll on a table.

In the world of software development, some tools are powerful but must be handled with care. The Singleton pattern is one of them: ensure a class has only one instance and provide a single, global way to access it1. TypeScript’s static members and access modifiers make it easy to implement a safe, type-aware Singleton, and many teams use Singletons for central services like configuration or logging. TypeScript is widely adopted in modern web tooling and frameworks, which is one reason patterns like this matter in real projects6.

What the Singleton Pattern Is and When to Use It

Imagine a medieval kingdom with only one official Royal Scribe. This person is the only one authorized to record royal decrees, so records remain consistent and authoritative. The Singleton pattern applies the same idea: restrict a class so only a single instance exists and provide a global access point to that instance.

Core purpose and analogy

The Singleton isn’t only about preventing extra objects; it’s about centralizing control. Like the Royal Scribe, a Singleton gives your codebase a single source of truth for a specific responsibility. Use it when a resource truly must be unique—for example, a single connection pool, a hardware interface, or a central configuration manager.

Singleton pattern at a glance

CharacteristicDescription & rationale
Single instanceClass is designed so only one instance exists (private constructor).
Global access pointA static method (e.g., getInstance()) provides access from anywhere.
Lazy initializationInstance is often created only when first requested, saving startup cost.
State managementCentral location for a piece of global state (settings, session info).

Practical use cases

Common, reasonable uses for Singletons include:

  • Logging services that funnel events into one stream or file.
  • Configuration management that provides consistent settings across modules.
  • Hardware adapters where multiple instances could conflict with the device.

Benefits and drawbacks

A balance scale comparing structured, observable design patterns with complex, tangled, and experimental code.

Benefits

  • Global access point simplifies usage across modules.
  • Lazy initialization conserves resources until needed.
  • Prevents duplicate instances of expensive resources.

Drawbacks

  • Tight coupling: consumers can hide dependencies by reaching into global state.
  • Global mutable state can cause hard-to-find bugs and test leakage.
  • Hidden side effects make reasoning and unit testing harder3.

Singletons complicate unit testing because they introduce global, persistent state. Tests can leak state between runs and mocking a Singleton is often awkward; that’s why many teams move toward dependency injection (DI) to make dependencies explicit and easier to replace in tests3.

How to implement a Singleton in TypeScript

TypeScript’s private constructor and static members provide a clear, type-safe way to implement Singletons2. Below is a practical example: a ConfigManager that loads and serves application settings.

Building a type-safe ConfigManager

class ConfigManager {
  private static instance: ConfigManager;
  private settings: Map<string, any> = new Map();

  private constructor() {
    console.log("Initializing ConfigManager instance...");
    this.settings.set("API_URL", "https://api.example.com");
    this.settings.set("TIMEOUT", 5000);
  }

  public static getInstance(): ConfigManager {
    if (!ConfigManager.instance) {
      ConfigManager.instance = new ConfigManager();
    }
    return ConfigManager.instance;
  }

  public get(key: string): any {
    return this.settings.get(key);
  }
}

// TypeScript prevents: const config = new ConfigManager(); // Error: constructor is private.

Using the Singleton in a service

class ApiService {
  private apiUrl: string;

  constructor() {
    const config = ConfigManager.getInstance();
    this.apiUrl = config.get("API_URL");
    console.log(`ApiService initialized with API URL: ${this.apiUrl}`);
  }

  public fetchData(): void {
    console.log(`Fetching data from ${this.apiUrl}...`);
    // Fetching logic here.
  }
}

console.log("Application starting...");
const service1 = new ApiService();
service1.fetchData();
const service2 = new ApiService();
console.log("Application finished.");

When you run this code, the ConfigManager initialization runs only once, showing both services share the same instance.

Why Singletons get criticized

Singletons look handy because they provide global access, but they can hide dependencies, introduce mutable global state, and make testing brittle. When a class silently reaches for a global instance, it hides a dependency that ought to be explicit in the constructor. That makes code harder to reason about and test3.

Concurrency and global state

Stateful Singletons can cause race conditions in concurrent scenarios. For example, a SessionCounter incremented concurrently without synchronization can produce lost updates. These timing-dependent bugs are difficult to reproduce and debug.

The testing conundrum

Singletons encourage tests that depend on execution order. State may leak between tests and mocks become awkward to inject. Dependency injection solves these problems by making dependencies explicit and replaceable.

Modern alternatives to Singletons

Dependency injection is the preferred modern approach for managing shared resources. DI makes dependencies explicit and greatly improves testability and modularity.

Dependency injection versus Singletons

Compare the ApiService that reads a global Singleton with a version that accepts a configuration manager via its constructor:

interface IConfigManager { get(key: string): any }

class ApiService {
  private apiUrl: string;
  constructor(config: IConfigManager) {
    this.apiUrl = config.get("API_URL");
  }
}

Now ApiService depends only on the IConfigManager contract. During tests you can pass a fake or mock, making tests predictable and fast.

By inverting control over who creates dependencies, components become more focused and flexible—this idea follows the Dependency Inversion Principle.

IoC containers and lifecycle control

Inversion of Control (IoC) containers manage object creation and injection. Frameworks and libraries such as NestJS and InversifyJS provide DI patterns and let you choose lifecycles (transient, scoped, or singleton-like) without the hidden coupling of a programmatic Singleton45.

Refactoring Singletons in a legacy codebase

Work incrementally. Identify where the Singleton is used, define an interface for its behavior, then refactor consumers to accept that interface via constructor injection. Wire the concrete instance at the composition root or let a DI container manage it.

Step 1: Identify and isolate

Find calls to MySingleton.getInstance() and define a clear interface that lists the public methods you need.

Step 2: Introduce DI incrementally

Refactor one consumer at a time:

  1. Change the constructor to accept the interface.
  2. Replace direct getInstance() calls with the injected instance.
  3. Pass the Singleton instance at the composition root until migration completes.

Step 3: Replace the Singleton with a managed instance

Once consumers accept dependencies via interfaces, remove the static getInstance() and make the implementation a plain class. Create one instance at the composition root or let a DI container handle lifecycle.

Key takeaways

  • Use Singletons sparingly and only when a service truly must be unique.
  • Prefer explicit dependency injection for better decoupling and testability.
  • If you use a Singleton, make it lazy and consider concurrency and thread safety.
  • For legacy systems, phase Singletons out by introducing interfaces and DI at the composition root.

Next steps for your team

Start a discussion about where a single shared instance is truly required. Prototype DI in a small module, adopt coding standards that favor explicit dependencies, and measure technical debt as you refactor. Pair programming and continuous feedback reduce risk during migration.

Consider internal resources:

Concise Q&A

Q: When should I choose a Singleton over DI? A: Only when a resource must be unique and stateless and the cost of making dependencies explicit outweighs the downsides. Even then, prefer creating a single instance at the composition root or using a DI container.

Q: How do I make Singletons safer for testing? A: Introduce an interface, refactor consumers to accept it via constructor injection, and inject a test double in unit tests. Migrate incrementally to avoid large regressions.

Q: How do I prevent concurrency bugs with Singletons? A: Keep Singletons stateless where possible. If state is required, add proper synchronization, atomic operations, or move state to scoped instances managed by a DI container.


1.
Martin Fowler, “Singleton,” Bliki. https://martinfowler.com/bliki/Singleton.html
2.
3.
Mark Seemann, “Singletons Are Pathological Liars.” https://blog.ploeh.dk/2010/07/28/SingletonsArePathologicalLiar/
4.
NestJS Documentation, “Dependency Injection.” https://docs.nestjs.com/fundamentals/injection
5.
InversifyJS Documentation. https://inversify.io/
6.
Stack Overflow, “Developer Survey 2023.” https://survey.stackoverflow.co/2023/
← Back to blog
🙋🏻‍♂️

AI writes code.
You make it last.

In the age of AI acceleration, clean code isn’t just good practice — it’s the difference between systems that scale and codebases that collapse under their own weight.

TypeScript Singleton Pattern: Complete Guide | Clean Code Guy