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;
    age:number;
    constructor(name:string,age:number,sex:string){
        this.name=name;
        this.age=age;
        this.sex=sex;
    }
    run(){
        return `${this.name}-${this.age}`
    }
}

Subcategories

class My extends Person{
    constructor(name:string,age:number,sex:string){
        super(name,age,sex)
    }
    run1(){
        console.log(this.name); // Report an error, private properties can only be used in its own class
        console.log(this.sex);  // 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(p.name);// Report an error, private properties can no longer be accessed outside the class
console.log(p.sex); // Report an error, protected types can only be accessed in this class or subclasses

Leave a Reply