What is the singleton pattern in Typescript

avatar

Borislav Hadzhiev

Fri Feb 19 20211 min read

banner

Photo by MXX SXX

How to create a singleton using private constructors in Typescript

A singleton is an OOP pattern where you only want to create a single instance of an object, which can then be reused.

For example say we have the following DatabaseConnection class and we want to ensure that our colleagues only use 1 instance of the class:

class DatabaseConnection {
  private static connection: DatabaseConnection;
  private todos: string[] = [];

  private constructor(private url: string) {}

  static getConnection() {
    if (this.connection) {
      return this.connection;
    }

    this.connection = new DatabaseConnection('localhost:123');
    return this.connection;
  }

  addTodo(text: string) {
    this.todos.push(text);
  }

  getTodos() {
    return this.todos;
  }
}

const dc1 = DatabaseConnection.getConnection();
const dc2 = DatabaseConnection.getConnection();

console.log(dc1 === dc2); // true

dc1.addTodo('walk the dog');
console.log(dc1.getTodos());

// Can't call, new DatabaseConnection(), because the constructor is private
// const dc3 = new DatabaseConnection()

We can see in the above snippet that the only way to create an instance of the DatabaseConnection class is to use the static getConnection method. That way we can ensure that the consumers of the API are only able to create a single instance of the class, because our constructor is private, therefore the class cannot be instantiated using the new keyword.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee