Currently, I am delving into TypeScript classes (though my experience with OOP is limited).
The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html
Here's the issue at hand:
I understand that accessing the protected property "name" directly like console.log(howard.name)
should not work, and it is permissible to access it through a method of a derived class.
Upon compiling this in TypeScript, I encounter an error message. However, upon opening the resulting JS file in the browser, I can observe the output in the Console, as if it were a public property.
Is this a normal occurrence in OOP? Why go through the trouble of creating classes with protected/private attributes in TypeScript if they ultimately end up being accessible in the compiled JS file anyway?
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error