DEV Community

KrishnaSai Polanki
KrishnaSai Polanki

Posted on

Access modifiers in TypeScript class Constructor

TypeScript includes a concise way to create and assign a class instance property from a constructor parameter.

For example if we want create a employee class with private property and should assign the value at the time of creating the instance in general we can do something like below.

export class Employee {
  private name: string;
    constructor(name: string) {
        this.name = name
    }
}
var emp = new Employee("Krishna");
Enter fullscreen mode Exit fullscreen mode

There is another way of doing it in Typescript which looks like below.

export class Employee {
  constructor(private name: string) {}
  updateEmployeeName(updatedName: string) {
    this.name = updatedName;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here we can notice that we used private access modifier to restrict accessing this property out side the class but within the class methods.

There are couple of other access modifiers which we can use to restrict the access of class properties.

public access modifier

If we prefix this keyword before the property in constructor it means we are telling the angular compiler to make it available out side the class.

export class Employee {
  constructor(public designation: string) {}
}
var emp = new Employee("SSE");
emp.designation = "";
Enter fullscreen mode Exit fullscreen mode

What will happen if we don't use any access modifier in the constructor for the property? It will not be available within the class itself except inside the constructor.

export class Employee {
  constructor(id: number) {
    id = 1;
  }
  updateEmployeeInfo() {
    this.id; //compilation error.
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's imagine if we want to make a property ready only property then we can do something like this

export class Employee {
  get Name() {
    return this.name;
  }
  constructor(id: number, private name: string, public designation: string) {}
}
var emp = new Employee(1, "Krishna", "SSE");
emp.Name = ""; //compilation error.
var name = emp.Name;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)