Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access TypeScript private members when I shouldn't be able to?

I'm looking at implementation of private members in TypeScript, and I find it a little confusing. Intellisense doesn't allow to access private member, but in pure JavaScript, it's all there. This makes me think that TS doesn't implement private members correctly. Any thoughts?

class Test{   private member: any = "private member"; } alert(new Test().member); 
like image 704
Sean Feldman Avatar asked Oct 03 '12 17:10

Sean Feldman


People also ask

How do I access private properties in TypeScript?

In TypeScript there are two ways to do this. The first option is to cast the object to any . The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch.

Can private members be accessed from subclass?

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. A nested class has access to all the private members of its enclosing class—both fields and methods.

What does private do in TypeScript?

Private keyword: The private keyword in TypeScript is used to mark a member private which makes it inaccessible outside the declared class. The fields are preceded by the private keyword to mark them private.

Does TypeScript have private?

TypeScript Private PropertiesUsing TypeScript, we can add private functionality into our classes. What are private properties or methods? A private property of method can only be accessed or called from the class instance itself.


1 Answers

Just as with the type checking, the privacy of members are only enforced within the compiler.

A private property is implemented as a regular property, and code outside the class is not allowed to access it.

To make something truly private inside the class, it can't be a member of the class, it would be a local variable created inside a function scope inside the code that creates the object. That would mean that you can't access it like a member of the class, i.e. using the this keyword.

like image 137
Guffa Avatar answered Sep 17 '22 18:09

Guffa