🎉 Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »

Singleton in TypeScript

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides single point of access to it for any other code.

Singleton has almost the same pros and cons as global variables. Although they’re super-handy, they break modularity of your code.

You can just use a class, which depends on Singleton, in some other context. You’ll have to carry the Singleton class as well. Most of the time, this limitation comes up during the creation of unit tests.

Learn more about Singleton

Usage of the pattern in TypeScript



Usage examples: A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in TypeScript code.

Identification: Singleton can be recognized by a static creational method, which returns same cached object.

Conceptual Example

This example illustrates the structure of the Singleton design pattern and focuses on following questions:

  • What classes does it consists of?
  • What roles do these classes play?
  • In what way the elements of the pattern are related?

After learning about the pattern’s structure it’ll be easier for you to grasp the following example, based on a real world PHP use case.

index.ts: Conceptual Example

 * The Singleton class defines the `getInstance` method that lets clients access
 * the unique singleton instance.
class Singleton {
    private static instance: Singleton;

     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
    private constructor() { }

     * The static method that controls the access to the singleton instance.
     * This implementation let you subclass the Singleton class while keeping
     * just one instance of each subclass around.
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();

        return Singleton.instance;

     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
    public someBusinessLogic() {
        // ...

 * The client code.
function clientCode() {
    const s1 = Singleton.getInstance();
    const s2 = Singleton.getInstance();

    if (s1 === s2) {
        console.log('Singleton works, both variables contain the same instance.');
    } else {
        console.log('Singleton failed, variables contain different instances.');


Output.txt: Execution result

Singleton works, both variables contain the same instance.

Singleton in Other Languages

Singleton in Java Singleton in C# Singleton in PHP Singleton in Python Singleton in Ruby Singleton in Swift