Access Modifiers in Angular TypeScript

Posted By : Milind Ahuja | 27-May-2018

Besides some amazing features of TypeScript, classes and the access modifiers are the most fundamental components of OO paradigm. The syntax we use in TypeScript to define classes is similar to the way what ES2015 offered.


Now, TypeScript does not only allows us to define classes but also to control the access to the property of the class that we defined. 


TypeScript supports the following modifiers:

1. Public: All the properties and methods could be accessed everywhere if they are declared as public.

2. Private: The private declared properties and methods can be accessed only within the class definition itself.

3. Protected: Properties and methods can be accessed from inside the class or any other class extending the one that owns the property or the method which are declared as protected.


For the proper understanding of the working of access modifiers, let us look at the following example:

class Person {  
     static totalPeople = 0;
     constructor(protected name: string, private age: number) {
       person.totalPeople += 1;
     /* code */
class Developer extends Person  {  
     constructor(name: string, private languages: string[], age: number){
       super(name, age);
    /* code */

In the example above, the access modifiers for properties: name, age and language are defined directly inside the constructor function. Let us try to access these by creating new instances of the classes.

let person = new Person("foo", 42);
person.age = 42; = "bar";

let dev = new Developer("foo", ["JavaScript", "HTML"], 26);
dev.languages = ["Angular"];

Errors will be thrown by the TypeScript for the age and name with message Property age is private and is only accessible inside class "Person" and the Property name is a protected and only accessible inside class "Person" and its subclasses respectively for Person class. In case of the class "Developer", the property language is defined as private and only accessible inside "Developer" class.


The access modifieres are something that is only utilized by the tools that statically analyze TypeScript code. At runtime, these access modifiers are meaningless as JS does't recognise them.


Also the TypeScript tools are not checking the template string for binding expressions that moght violate the TypeScript rules. This is why, it doesn't matter for the template whether the property is private, public or protected.

In future, we might see the improvement in terms of template analyzing functionality.


Request for Proposal

Recaptcha is required.

Sending message..