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.
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.
Contact Us