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");
}
}
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.
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With