This page looks best with JavaScript enabled

Access modifiers in Typescript

 ·   ·  ☕ 2 min read

Typescript supports public, private and protected modifiers that affect the accessibility of class in different ways.

Access modifiers further a core concept of object oriented programming - ‘encapsulation’. The accessibility of variables and members of a class are driven by modifiers and therefore controlled in the programming flow.

Let’s start with a simple class example.

1
2
3
4
5
class MathOp {
    public x:number;
    private y: number;
    protected z: number;
}

Public modifier

All variables and members are public by default in Typescript.

So, I may as well type -

1
2
3
class MathOp {
  x: number;
}

.. and no one will leave the chat.

Public variables and members are accessible by anybody outside the class.

1
2
3
const op = new MathOp();
console.log(op.x);
// 1

Let’s add and test a method in the class -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MathOp {
  x: number = 1;

  double(x: number): number {
    return x * x;
  }
}

const op = new MathOp();
console.log(op.double(3));
// 9

Private modifier

Private modifiers are not accessible outside the class.

1
2
3
4
5
6
7
class MathOp {
  private y: number = 1;
}

const op = new MathOp();
console.log(op.y);
//  error TS2341: Property 'y' is private and only accessible within class 'MathOp'.

Private variables are accessed through members - if at all they need to be accessed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MathOp {
  private y: number = 1;

  getY(): number {
    return this.y;
  }
}

const op = new MathOp();
console.log(op.getY());
// 1

Members behave the same way as variables. Private members are used to perform operations within the class.

1
2
3
4
5
6
class MathOp {
    private myFunc:void {
        // do stuff
    }
}

Protected modifier

Protected members can be accessed within the class and by the derived classes. They cannot be accessed outside of that scope.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class MathOp {
  protected z: number = 3;
}

class newMathOp extends MathOp {
  constructor() {
    super();
    console.log(this.z);
  }
}

const newOp = new newMathOp();

/* output
 3
*/

Protected variables and members are not accessible from extended-class instances as well as class instances.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things