TypeScript public/protected/private example

TypeScript lets you do inheritance in Javascript, but the restrictions are enforced at compile time, rather than the typical Javascript tendency to randomly throw errors whenever the browser feels like it.

Part of this is enforcement of access specification:

class Dialog {
    message: String;
   
    render() {
    }
 
    public e() {
        console.log("e");   
    }
    
    protected f() {
        console.log("f");
    }
    
    private g() {
        console.log("g");
    }
}

class AlertDialog extends Dialog {
     render() {
         this.e();
         this.f();
     }    

     public e() {
          super.e();
         console.log("e - child"); 
     }     
     protected f() {
         console.log("f - child");
     }
}

let ad: Dialog = new AlertDialog();
ad.render();

This prints out the following:

e
e - child
f - child

From this you can see that you can’t call private methods outside their own class, and protected methods are automatically virtual methods that override the parents. Public is available as an access specifier for completeness, but not necessary.