Alex Maiburg
Alex Maiburg

Reputation: 690

Incorrect accessing protected members of a class shows no error in console

I executed a simple example of TypeScript documentation about classes where it says:

The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes... Notice that while we can’t use name from outside of Person, we can still use it from within an instance method of Employee because Employee derives from Person.

When I execute it in stackblitz the editor complains correctly.

enter image description here

However the 2nd console.log, which accesses the name property from outside the class or its subclass outputs the name in the console without any errors.

enter image description here

Shouldn't it throw an error? What did I miss?

Upvotes: 0

Views: 51

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249666

The current implementation of private /protected members are only a compile time checked constraint. You can easily get around it at runtime. When the ecma script proposal for private fields is accepted we will get true privates, until the this is the best we have.

Upvotes: 1

Related Questions