To declare a private constructor in TypeScript, we need to prefix private
keyword to the constructor declaration. A private constructor cannot be created from outside of the class.
It is also important to note that when we declare a private constructor, we cannot create multiple instances of a class (singleton pattern).
class Singleton {
private constructor() {}
}
let singleton = new Singleton(); // NOT ALLOWED
Typescript will throw an error, Constructor of class 'Singleton' is private and only accessible within the class declaration.
So the question here is, how can we create an instance from within a class?
We can make use of the static property to create an instance of the Singleton class.
First, we will declare a static private field called instance
which will be of type Singleton
. Next, we will declare a static method called getInstance()
which will check if an instance of the Singleton class is created. If it is not created, it will instantiate the object.
class Singleton {
private static instance: Singleton;
private constructor(public name: string) {}
static getInstance() {
if (this.instance) return this.instance;
this.instance = new Singleton("Bob");
return this.instance;
}
}
let singleton = Singleton.getInstance();
console.log(singleton); // Singleton {name: 'Bob'}
Once the instance is created, the getInstance()
method will always return the object that was created during the initial call. This way the private constructor method cannot create multiple instances of the class.
let singleton1 = Singleton.getInstance(); // Singleton {name: 'Bob'}
let singleton2 = Singleton.getInstance(); // Singleton {name: 'Bob'}
let singleton3 = Singleton.getInstance(); // Singleton {name: 'Bob'}
Calling getInstance()
multiple times will not create a new instance.