Understanding Constructors in TypeScript

In TypeScript a constructor is a method in a class that gets triggered when an instance of it is created and is usually utilized to set the member properties of the object.

Example: In this example, the default constructor is public permitting the instantiation of Example from any location.

JavaScript
class Example {
  constructor(public name: string) {
    this.name = name;
  }}
const example = new Example('TypeScript');
console.log(example.name); 

Output:

TypeScript

Private & Protected Constructors in TypeScript

Constructors are important in creating objects within classes while using TypeScript, in this by default constructors are public and thus can be called from any location. At times though, you may want to stop any other person from creating instances of your class – that is where we come across private and protected constructors.

Similar Reads

Understanding Constructors in TypeScript

In TypeScript a constructor is a method in a class that gets triggered when an instance of it is created and is usually utilized to set the member properties of the object....

Private Constructors

You can use a private constructor to create a class which cannot be instantiated from outside that class most especially when implementing the Singleton pattern or when you plan on making a class static....

Protected Constructors

When you want to create a base class, which should not be instantiated directly but allows subclassing, a protected constructor will restrict the instantiation of a class from outside the class and its subclasses....

Use Cases

When to Use Private Constructors...

Conclusion

Class instantiation in Typescript can be controlled using private as well as protected constructors. By means of these access modifiers, one can enforce patterns like singleton or static classes and define abstract base classes, by understanding these concepts it improves the ability to come up with strong TypeScript programs that are easy to manage....

Contact Us