Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

TypeScript Public, Private, Protected and Readonly Modifiers!

TypeScript Modifiers

The TypeScript supports to multiple modifiers and it is by default public.
1.     Public,
2.     Private,
3.     Protected and
4.     Read-only

Public by default! Stayed Informed – Learn Angular 2 with TypeScript

Public Modifier – Public by default! It is freely access anywhere.
In the below example, the class Employee and its members are by default public and we are freely access it.

Example –
class Employee {
empName: string;
constructor(name: string) {
this.empName = name;
}

salary(salary: number = 10000) {
console.log('Hello, ' + this.empName + ' Your Salary -' + salary);
}
}

let empSal = new Employee("Anil");
console.log(empSal.salary());
console.log(empSal.salary(40000));

Private Modifier -When using private modifier, we can’t be accessed from outside of its containing class.

Example as,
class Employee {
private empName: string;
constructor(name: string) {
this.empName = name;
}

salary(salary: number = 10000) {
console.log('Hello, ' + this.empName + ' Your Salary -' + salary);
}
}

let emp = new Employee("Anil").empName;
//error: property 'empName' is private and only accesible in the class 'Employee'.

Protected Modifier - The protected modifier is very similar to private but only one difference that can be accessed by instances of deriving classes.

Example as,
class Employee {
protected empName: string;
constructor(name: string) {
this.empName = name;
}

salary(salary: number = 10000) {
console.log('Hello, ' + this.empName + ' Your Salary -' + salary);
}
}

class Employer extends Employee {
private department: string;

constructor(empName: string, department: string) {
super(empName);
this.department = department;
}

salary(salary = 20000) {
super.salary(salary);
}
}

let empSal = new Employer("Anil", "IT");
console.log(empSal.salary());
console.log(empSal.empName); //error- the property 'empName' is protected and only accesible within the class 'Employee' and its child class.

Readonly Modifier - Read-only properties must be initialized at their declaration or in the constructor.

For example as,
class Employee {
readonly empName: string;
constructor(name: string) {
this.empName = name;
}

salary(salary: number = 10000) {
console.log('Hello, ' + this.empName + ' Your Salary -' + salary);
}
}

let emp = new Employee('Anil');
emp.empName = 'Anil Singh';//error - cannot assign to 'empName' because it is constant or readonly.

Stayed Informed – Learn Angular 2 with TypeScript

I hope you are enjoying with this post! Please share with you friends. Thank you!!


This post first appeared on Programming, please read the originial post: here

Share the post

TypeScript Public, Private, Protected and Readonly Modifiers!

×

Subscribe to Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×