cbdeveloper
cbdeveloper

Reputation: 31335

Class with protected / private field written in TypeScript can be accessed from outside the class in JavaScript?

I'm currently studying classes in TypeScript (and I don't have that much experience in OOP).

The snippet below is from classes chapter in https://www.typescriptlang.org/docs/handbook/classes.html

Here is the thing:

I get that it should not be able to access the protected property "name" directly, as in console.log(howard.name) and I know that it should be ok to access it through a method of a derived class.

I do get an error message when I compile this on TypeScript. But the fact is that when I open the resulting JS file on the browser (compiled), I can see the output in the Console, just like if it were a public property.

Is this normal in OOP? Why bother creating classes with protected/private attributes in TypeScript if they will be accessible anyway in the JS compiled file?

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

Upvotes: 0

Views: 2187

Answers (1)

deceze
deceze

Reputation: 522005

Visibility modifiers (protected, private) are not there for "security" or to "hide" anything. It won't protect data from being accessed. What it's there for is to establish safe interfaces for your classes/objects. If you classify something as public, that means other code can be written against that property. That means that property should preferably not change in the future or you risk breaking other code. protected and private properties are much more restricted in where they can be used from, which gives you better guarantees for what will break when you change them and who will be messing with those values.

Javascript itself does not have any notion of visibility modifiers, it's all public in Javascript. Those are only enforced at the time of Typescript compilation, at which point you'll be notified if you're violating your own contracts. But that check does not exist at runtime.

Upvotes: 7

Related Questions