Skip to content
Advertisement

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);

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement