Search code examples
typescriptprivate-constructor

What is the usage of Private and Protected Constructors in Typescript


I noticed that in Typescript you can define constructor to be with any access modifier (private, protected, public). What will be the usage of this can someone give a valid example how to use private and protected constructors in Typescript ?

Example this is a valid code in Typescript:

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

Solution

  • 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;
        }
    }