Private, Public & Protected: Access Modifiers In Typescript

Vijay TembugadeVijay Tembugade
5 min read

Let’s try to understand the most important keywords in typescript, which are public, private, and protected. These things are really helpful while building large applications.

Disclaimer: Having a good understanding of JavaScript and an idea about typescript will help you to understand this blog much more clearer. You can play around the code on online typescript play ide.

If you have been through Java background, you would have heard the word ‘Access Modifiers’ in classes. Let's see those in Typescript.

What are these ‘Access Modifiers’?

We define the Class and it has words like private, public, and protected, these words, that define how a variable should be modified or available to access within the scope or beyond the scope of it, are called “Access Modifiers.”

Access modifiers are keywords used to specify the accessibility of a class (or type) and its members. These modifiers can be used from code inside or outside the current application.

In JavaScript, we can define private variables and methods in a Class. But, doing it in Typescript, gives us a clear and defined way to work. You can read about private variables and methods of javascript on MDN docs.

Here is one small example I found on Quora to explain about Access modifiers:

Think of the class as a human. Whatever is public is what information the human makes public to the world for anyone to access. Whatever information is protected is what only humans directly related to the original person can access (stuff only the kids know where it is hidden and they can change it or mess with it). Private is what no one can access (like thoughts not said). People can request to hear the thoughts and request a change in thought but only the original human can make the actual change.

Defining a class in Typescript :

Most of the time we say, Class is the blueprint of an object. Let's see, how we can create this blueprint of objects with help of the class. Let's create a class UserData

class UserData {
        // in typescript we declare type as below for properties of class.  
    email: string;
    name: string;
    city: string;

    constructor(email:string, name: string, city: string){
        this.email = email;
        this.name = name;
                this.city = city;
    }
}

const user = new UserData("example@email.com", "John", "LA");
console.log(user.city) // LA

But, here is a catch. We can see that we can access email, name, and city outside of the class. So, sometimes, we need to keep things private and we want these things to be modified from class only.

Public key

public defines that, variables or properties are accessible inside the class, outside of the class, and any class which inherits from this class. If we do not define private or protected then by default it is treated as public property.

class UserData {
    public email: string; // it is public as defined
    name: string; // it is by default public
    public city: string; // it is public as defined.

    constructor(email:string, name: string, city: string){
        this.email = email;
        this.name = name;
                this.city = city;
    }
}

const user = new UserData("example@email.com", "John", "LA");
console.log(user.city) // LA

Private key

So, let's assume, We don't want the city should not be visible outside of the class, then we can assign the city to the private key and it will not be available outside of the class.

class UserData { 
    email: string;
    name: string;
    private city: string; // city as 'private' access modifier

    constructor(email:string, name: string, city: string){
        this.email = email;
        this.name = name;
                this.city = city;
    }
}

const user = new UserData("example@email.com", "John", "LA");
console.log(user.city) // error: Property 'city' is private 
// and only accessible within class 'UserData'.

So, if we try to log city outside of the class it will give us an error, which will say, Property 'city' is private and only accessible within class 'UserData'.

But, using private has one issue. Let's see what is an issue with private. Create another class UserDataWithAge that inherits from UserData and tries to access private city in the inherited class.

class UserData { 
    email: string;
    name: string;
    private city: string; // city as 'private' access modifier

    constructor(email:string, name: string, city: string){
        this.email = email;
        this.name = name;
                this.city = city;
    }
}

class UserDataWithAge extends UserData{
  age: number;
  constructor(email: string, name: string, city: string, age: number){
    super(email, name, city)
    this.age  = age;
  }
  consoleLogCity(){
    console.log(this.city) // Property 'city' is 
     // private and only accessible within the class 'UserData'.
  }

  consoleLogName(){
    console.log(this.name) // Joe
  }
}

const user = new UserDataWithAge('exaple@email.com', 'Joe', 'NY', 30);
user.consoleLogUser();
user.consoleLogCity();

In the above example, when we see in consoleLogCity that city is not accessible, as it is private in class UserData and we get an error saying, Property 'city' is private and only accessible within class 'UserData'.

So, here the question arises, how it is we can access the city in an inherited class? And here, comes a protected access modifier.

Protected Key

Let's see, how we can use protection to solve the above problem. In the above code, change the access modifier of the city from private to protected.

class UserData { 
    email: string;
    name: string;
    protected city: string; // city as 'protected' access modifier

    constructor(email:string, name: string, city: string){
        this.email = email;
        this.name = name;
                this.city = city;
    }
}

class UserDataWithAge extends UserData{
  age: number;
  constructor(email: string, name: string, city: string, age: number){
    super(email, name, city)
    this.age  = age;
  }
  consoleLogCity(){
    console.log(this.city)
  }

  consoleLogName(){
    console.log(this.name) 
  }
}

const user = new UserDataWithAge('exaple@email.com', 'Joe', 'NY', 30);
user.consoleLogName()
user.consoleLogCity()

In the above example, you won't see any errors, saying the city is not accessible in UserDataWithAge class. But, if try to access city outside of both classes then it will give us an error :

// ....
// both class code
// ...
const user = new UserDataWithAge('exaple@email.com', 'Joe', 'NY', 30);
console.log(user.city);
// Error : Property 'city' is 
// protected and only accessible within class 'UserData' and its subclasses.

Here, the city is not accessible because it is protected. So, protected defines that properties of the class will be available in inherited classes also, but not available outside of inherited classes.

This is about access modifiers in typescript i.e private, protected, and public.,

If you like the blog, feel free to connect with me on LinkedIn and Twitter

9
Subscribe to my newsletter

Read articles from Vijay Tembugade directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vijay Tembugade
Vijay Tembugade