What is the singleton pattern in Typescript


Borislav Hadzhiev

Fri Feb 19 20211 min read


Photo by MXX SXX

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.