Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of Private and Protected Constructors in Typescript

Tags:

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");
    }
}
like image 303
Hivaga Avatar asked Jul 02 '18 10:07

Hivaga


People also ask

What is protected constructor in TypeScript?

If you declare your constructor as protected, on the other hand, while your class still cannot be instantiated from external code, it can be extended. A protected constructor can be used by code within the class (like the private constructor) and also by code in a class that extends it.

What is the difference between private and protected in TypeScript?

Private - A private member cannot be accessed outside of its containing class. Private members can be accessed only within the class and even their sub-classes won't be allowed to use their private properties and attributes. Protected - A protected member cannot be accessed outside of its containing class.

What is the use of private constructors?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

What does Protected do in TypeScript?

protected implies that the method or property is accessible only internally within the class or any class that extends it but not externally. Finally, readonly will cause the TypeScript compiler to throw an error if the value of the property is changed after its initial assignment in the class constructor.


1 Answers

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;
    }
}
like image 68
Titian Cernicova-Dragomir Avatar answered Oct 21 '22 18:10

Titian Cernicova-Dragomir