Actually the answer to this question is rather simple.
You have this code:
class Test{
private member: any = "private member";
}
alert(new Test().member);
In that code, you are mixing two different languages. This part is TypeScript:
class Test{
private member: any = "private member";
}
and this part is JavaScript:
alert(new Test().member);
The private
keyword in the Test
class for member
field is for TypeScript. Thus other classes within TypeScript cannot access the member
field because the TypeScript compiler will not allow it. For example, if you tried this, it will not work:
class Test2 {
constructor() {
var test = new Test();
test.member = "Cannot do this";
}
}
It makes no difference whether you put private
or public
on the generated JavaScript. The generated JavaScript code will always be:
var Test = (function () {
function Test() {
this.member = "private member";
}
return Test1;
}());
Therefore, you are able to do this because JavaScript will allow this:
alert(new Test().member);
This is not a rule carved in stone and there may be cases that I am not aware of but if you are using TypeScript, then why worry about what you are allowed to do using JavaScript; the idea is that you are no longer writing JavaScript so what you can/cannot do in JavaScript should not be something to worry about anymore. To me this worry would be the same as writing C# code and then saying how come I am able to change the private field in CIL or assembly language. I am not sure if CIL allows it or not, but that is not the point. The point is you just don't go poking around in what you can do with CIL after you write code in C#.
There may be cases where you write code in TypeScript but the public may use the generated JavaScript, a plugin perhaps, and you don't want them to break things, well in that case you would worry about it. For those cases, you would write your TypeScript code to make the fields private
even on the JavaScript side. Other answers have already covered on how to do that.