×

Access Modifiers in TypeScript

Amit Kumar  Print   4 min read  
14 May 2022
 
Intermediate
47.2K Views

Like others programming languages, TypeScript supports access modifiers at the class level. The access modifier in TypeScript is quite useful and recommended because it preserves the security of the class members such as properties and attributes and prevents them from being used inappropriately. We can also use it to control the accessibility of the data members of a class so that It can not be used abruptly anywhere in the script file. If the class does not have to be set any access modifier, the TypeScript automatically sets the public modifier access to all class members as a default modifier

TypeScript supports three access modifiers - public, private, and protected.

  1. Public - By default, members (properties and methods) of the TypeScript class are public - so you don’t need to prefix members with the public keyword. Public members are accessible everywhere without restrictions even from the multiple level sub-classes without any compile errors.

  2. Private - A private member cannot be accessed outside of its containing class. Private members can be accessed only within the class and even their sub-classes won't be allowed to use their private properties and attributes.

  3. Protected - A protected member cannot be accessed outside of its containing class. Protected members can be accessed only within the class and by the instance of its sub/child class.

In compiled JavaScript code, there will be no such type of restriction on the members.accessmodifiers.ts

class Foo {
 private x: number;
 protected y: number;
 public z: number;
 saveData(foo: Foo): void {
 this.x = 1; // ok
 this.y = 1; // ok
 this.z = 1; // ok

 foo.x = 1; // ok 
 foo.y = 1; // ok 
 foo.z = 1; // ok
 }
}

class Bar extends Foo {
 getData(foo: Foo, bar: Bar) {
 this.y = 1; // ok
 this.z = 1; // ok

 bar.y = 1; // ok
 bar.z = 1; // ok
 foo.z = 1; // ok

 foo.x = 1; // Error, x only accessible within A 
 bar.x = 1; // Error, x only accessible within A 
 bar.y = 1; // Error, y only accessible through instance of B 
 }
}

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

accessmodifiers.js

var Foo = (function () {
 function Foo() {
 }
 Foo.prototype.saveData = function (foo) {
 this.x = 1; 
 this.y = 1; 
 this.z = 1;
 foo.x = 1; 
 foo.y = 1; 
 foo.z = 1;
 };
 return Foo;
}());
var Bar = (function (_super) {
 __extends(Bar, _super);
 function Bar() {
 return _super.apply(this, arguments) || this;
 }
 Bar.prototype.getData = function (foo, bar) {
 this.y = 1; 
 this.z = 1;
 bar.y = 1; 
 bar.z = 1;
 foo.z = 1;
 foo.x = 1;
 bar.x = 1; 
 bar.y = 1; 
 };
 return Bar;
}(Foo));

Readonly Modifiers

TypeScript supports readonly modifiers on property level by using the readonly keyword. The Readonly properties must be initialized at their declaration or in the constructor.

By using the readonly modifiers, we provide the read-only access modifier to mark a class property as immutable, and the basic example is given below that demonstrates how to use readonly modifiers.

readonly.ts

class Company {
 readonly country: string = "India";
 readonly name: string;

 constructor(_name: string) {
 this.name = _name;
 }
 showDetails() {
 console.log(this.name + " : " + this.country);
 }
}

let c1 = new Company("Dot Net Tricks Innovation");
c1.showDetails(); // Dot Net Tricks Innovation : India

c1.name = "TCS"; //Error, name can be initialized only within constructor

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

readonly.js

var Company = (function () {
 function Company(_name) {
 this.country = "India";
 this.name = _name;
 }
 Company.prototype.showDetails = function () {
 console.log(this.name + " : " + this.country);
 };
 return Company;
}());
var c1 = new Company("Dot Net Tricks Innovation");
c1.showDetails();
c1.name = "TCS";

Accessors

Just like C# properties accessors, TypeScript supports get/set accessors to access and to set the value to a member of an object. This way gives us control over how a member of an object is accessed and set.

TypeScript supports two types of accessors such as to get() and set() and if we have to get() accessor defined but no set() then the value will act as a read-only property eventually.

Note: With the release of TypeScript 4.3 and above, we can have different types of getting and setting accessors.

accessors.ts

class Employee {
 private passcode: string;
 private _fullName: string;

 constructor(_passcode?: string) {
 this.passcode = _passcode;
 }
 get fullName(): string { //accessing value
 return this._fullName;
 }
 set fullName(newName: string) { //setting value
 if (this.passcode == "secret_passcode") {
 this._fullName = newName;
 }
 else {
 console.log("Error: Unauthorized update of employee!");
 }
 }
}

let e1 = new Employee("secret_passcode");
e1.fullName = "Shailendra Chauhan";
if (e1.fullName) {
 console.log(e1.fullName);
}

let e2 = new Employee();
e2.fullName = "Kanishk Puri"; //Error: Unauthorized update of employee 
if (e2.fullName) {
 console.log(e1.fullName);
}

The compiled JavaScript (ES5) code for the above TypeScript code is given below:

accessors.js

var Employee = (function () {
 function Employee(_passcode) {
 this.passcode = _passcode;
 }
 Object.defineProperty(Employee.prototype, "fullName", {
 get: function () {
 return this._fullName;
 },
 set: function (newName) {
 if (this.passcode == "secret_passcode") {
 this._fullName = newName;
 }
 else {
 console.log("Error: Unauthorized update of employee!");
 }
 },
 enumerable: true,
 configurable: true
 });
 return Employee;
}());
var e1 = new Employee("secret_passcode");
e1.fullName = "Shailendra Chauhan";
if (e1.fullName) {
 console.log(e1.fullName);
}
var e2 = new Employee();
e2.fullName = "Kanishk Puri"; //Error: Unauthorized update of employee 
if (e2.fullName) {
 console.log(e1.fullName);
}

Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

Accept cookies & close this