Access modifiers in Typescript

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.

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 -

class MathOp {
  x: number;
}

.. and no one will leave the chat.

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

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

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

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.

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.

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.

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.

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.

comments powered by Disqus