Typescript: Are “Private” properties private?
If you are reading this article, I guess you are interested in the Typescript language. Either you are a newbie or an experienced developer in Typescript language, I bet you use the concept
private for class properties many times. But do you know that it is not
private at all. Let’s discover together.
Take a look at an example where I have a Student class:
As you can see there are two private properties in the class: attribute
phone and method
playGame() and we expect that the outside of the class cannot call these properties. And yes, the Typescript compiler guarantees the rule for us.
index.js I import the class and I try to violate the rule:
With the modern IDEs and useful plugins, developers can be alerted if they do like this. How luckily we are, right!
But, even you use a simple text editor to write these lines of code. The Typescript compiler will throw errors when building:
So, I can violate the rule by cast the
Student instance as
any and this is the compiled result:
Then, in runtime, it works. Of course, use
any is a bad practice or even a mistake. My point here is to prove that we can call
But you can have real
With private lass fields. We can easily achieve real
private properties. There is however a stage 3 proposal to allow defining private class fields using a hash
# prefix. I will modify the class
Student as below:
You can see now, the attribute
phone is changed to
#phone and the method
playGame() is changed to
#playGame. I keep the same main file with the trick
student as any and you can see the result when compiling the code:
The compiler throws an error and the compiling process is exited at the first line of code that the rule is violated. We can see it is more restricted than before where it throws errors for all of the violated lines of code.
You can check more examples in private class fields documentation.
That’s it! I hope you have found a cool knowledge of Typescript. If you have other opinions, please let me know by leaving the comment below.
Keep calm and enjoy programming!
If you like the post, you can buy me a Coffee at https://ko-fi.com/tlcong.