3.4 Access modifiers

TypeScript allows us to use some of the reserved keywords private, public and protected to control the access to class methods and properties.

  • Public members are directly accessible by both the base and derived class.
  • Private members are only accessible within the class defining them.
  • Protected members are accessible in the class that defines them and in classes that inherit from that class.

Getting Ready

All you need to be able to use access modifiers is an installation of TypeScript 2.0 or higher.

How to do it…

Let’s declare a class named Base with public, private and protected properties and methods:

class Base {
	protected msg = 'Protected!';

	private _doPrivate() {
		console.log('Private! ');
	}

	public doPublic() {
		console.log('Public!');
	}

	public accessPrivate(){
		this._doPrivate();
	}
}

How it works…

Now, let’s declare a derived class and create an instance to see how the access modifiers behave:

class Derived extends Base {
	public accessProtected() {
		this.msg;
	}
}
 const derived = new Derived();

If we try to invoke the class methods and properties, we will be able to observe the access modifiers rules in action:

derived.doPublic();        // OK
derived.accessPrivate();   // OK
derived.accessProtected(); // OK
derived.msg;               // Error
derived._doPrivate();      // Error

Source Code

Access modifiers


Shiv Kushwaha

Author/Programmer