Modifiers for typescript classes

Those who have learned java should understand it very well, but write it anyway!

typescript gives us three modifiers when defining properties inside.

  1. public : public Accessed inside the current class, subclasses and outside the class
  2. protected : protected type can be accessed inside the current class and subclasses, but not outside the class
  3. private : private can be accessed inside the current class, but not outside the class

Properties without modifiers are public by default.

Parent Class

class Person{
    private name:string;
    protected sex:string;
        return `${}-${this.age}`


class My extends Person{
        console.log(; // Report an error, private properties can only be used in its own class
        console.log(;  // Correct, protected types can be used in subclasses
        console.log(this.age);  // Correct
var p = new Person("TOM",23,"Male");
console.log(p.age); // Correct, public can be accessed in this class, subclasses, and outside the class
console.log(;// Report an error, private properties can no longer be accessed outside the class
console.log(; // Report an error, protected types can only be accessed in this class or subclasses

Leave a Reply