Typescript is object oriented programming language like Java, C# if you know in every object oriented programming there is term called Access Modifiers which is really useful and important hence necessary to learn and understand.
Access Modifiers are used achieve encapsulation.
Today in this tutorial I am going to give you complete understanding on Access Modifiers which is going to help you working with Angular or React projects.
Table of Contents
What is Typescript Access Modifiers ?
Access modifiers is basically the keywords that we can apply to the member of the class to control access from the outside of the class.
In typescript we can add access modifiers in the class so let’s say you do not want allow access to certain properties from the class to outside of it’s scope that when we use modifiers.
There are three modifiers available in TypeScript, those are public, private and protected.
public
Public keyword is used to provide public access to the class members, meaning those properties and method will be accessible outside the class using object of the class itself.
By default Public is the default access modifiers for all properties and methods so if you define any properties or method without access modifiers that will be consider as public and then as name suggests it can be accessible outside the class.
private
Private keyword is used to make particular property or method private which mean it can not be accessible out side the class.
protected
Protected is used to make class members protected from accessing outside the class, it can only be accessed inside the class and sub or child class or we can also call it in derived class.
Don’t get confuse with protected keyword it is simple just think as private keyword with additional feature of being accessible into the child class.
When to use Access Modifiers in Typescript?
So it is simple enough whenever we want to control the accessibility of particular property of a method we use Access modifiers.
Sometime we needs to keep class properties separate from the outside of class, basically we do not want to allow change value of particular property using the class object then that is where we use access modifiers.
As you start getting into the practical you will see the importance using it, additionally here in this tutorial I am also going to show few examples.
Advantage of using access Modifiers in Typescript
- It makes our program more readable and maintainable
- It reduces the chances of bugs and avoid logical errors.
- Properties and methods are more encapsulated.
What is the need of using access Modifiers in Typescript?
After seeing advantages above answer is really simple the needs is really important – which is to implement the encapsulation meaning to wrap our data into the single container.
How to use Access Modifier in Typescript?
Example of using public keyword:
As I told you by default all class members are public, here is the quick example:
class Calculation {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add() {
console.log(this.x + this.y);
}
}
let calc = new Calculation(10, 2);
calc.add();
Output:
$ tsc main.ts && node main.js
12
If you are not sure how run your typescript program then take help from this tutorial to setup your development machine – How to install TypeScript and Write TypeScript Program
Here is how we can access and change the value of property:
class Calculation {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add() {
console.log(this.x + this.y);
}
}
let calc = new Calculation(10, 2);
calc.y = 8;
calc.add();
Now the output is 18 because we change the value of y
variable outside the class.
$ tsc main.ts && node main.js
18
Example if using Private Keyword
We will take the same example and see what happens if we declare private keyword for the property.
class Calculation {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add() {
console.log(this.x + this.y);
}
}
let calc = new Calculation(10, 2);
calc.y = 8;
calc.add();
If you see as soon we added private keyword the editor start giving and error – Property ‘y’ is private and only accessible within class ‘Calculation’.ts(2341)
And if you try compiling same code using typescript compiler then it will give the same error
So remove error line where we were assigning new value to y variable outside the class and compile the program it should work as intended.
Example if using Protected Keyword
Protected access modifier is similar to the private access modifier with only one difference that the protected members can be accessed using their child classes.
Now here I am going to create two classes where class User will extends from class Company
class Company {
protected companyName: string;
constructor(companyName: string) {
this.companyName = companyName;
}
}
class User extends Company {
protected name: string;
protected role: string;
constructor(companyName: string, name: string, role: string) {
super(companyName);
this.name = name;
this.role = role;
}
profile() {
console.log(`Company Name: ${this.companyName}`);
console.log(`User Name: ${this.name}`);
console.log(`User role: ${this.role}`);
}
}
let user = new User('Test', 'Yogesh', 'Manager');
user.profile();
If you see in the above example User class is the sub of class of Company class hence it’s protected and public members will be accessible into the User class.
Like we are accessing CompanyName property here similarly you can access the method as well.
Important note: If you parent class is having constructor defined then don’t forget to call super() method inside you child class and pass required arguments to the constructor of parent class.
Now if you compile and run above example you should following output written on console.
$ tsc main.ts && node main.js
Company Name: Test
User Name: Yogesh
User role: Manager
What’s Next?
So you have learn all the necessary part of using access modifiers in typescript, next let’s learn a very good best practice and essential feature from constructor.
It is refactoring constructor function using Access Modifiers along with constructor parameter, read this complete tutorial to get understanding of using it – How to add Access Modifiers with Constructor Parameters in TypeScript