What is the usage of Private and Protected Constructors in Typescript

Just as in other languages the usage of this would be to not actually allow anyone (except for the class itself) to instantiate the class. This might be useful for example with a class that only has static method (a rare use case in Typescript as there are simpler ways to do this), or to allow a simple singleton implementation:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private static _a :A
    static get(): A{
        return A._a || (A._a = new A())
    }
}

Or special initialization requirements that require using a factory function. FOr example async init:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private init() :Promise<void>{} 
    static async create(): Promise<A>{
        let a = new A()
        await a.init();
        return a;
    }
}

This could be used for the singleton pattern.

One of the approaches to this is not letting the external code create instances of the class at all. Instead, we use static accessor:

class SingletonExample {

    private constructor() {
        console.log('Instance created');
    }

    private static _instance: SingletonExample | undefined;

    public prop = 'value';

    public static instance() {
        if (this._instance === undefined) {
            // no error, since the code is inside the class
            this._instance = new SingletonExample();
        }
        return this._instance;
    }

}

const singleton = SingletonExample.instance(); // no error, instance is created
console.log(singleton.prop); // value
const oops = new SingletonExample(); // oops, constructor is private

Tags:

Typescript