Paul Galvin
3 min readOct 13, 2015

Private Members in TypeScript Are Not Always Private

I recently stumbled across the fact that “private” classes and their members are not very private outside of the warm and fuzzy confines of your TypeScript compiler. This is entirely unsurprising once you think about it (or in my case, accidentally experienced it) and hardly a kept secret by anyone. Here’s an example that shows how un-private these things are outside of the TypeScript compiler environment itself.

In the setup to this, I have a class as follows:

That class must have something to hide

The DontLookAtMe class has three private members. I create three just for the heck of it — just one would serve as demonstration.

I create a placeholder for this class like this:

Lastly, I new it up and log it to the console:

It feels kind of mean to log it out when it really just wants to be left alone

This is what you get in the Chrome console:

Those members are not very hidden

So that’s interesting. Those “private” fields are quite visible to Chrome with a simple console.log(). But does that prove very much? Maybe not — Chrome’s developer tools are privileged and maybe they give us special insight not available to “regular” runtime execution contexts. Here’s some more proof. I actually learned about this whole thing when I accidentally referenced some private fields in the view of an angular app. This is what that looks like courtesy of my contrived example:

You can’t run, you can’t hide — I’ll find you

And the output is:

The final insult

At run-time, Angular is perfectly happy to find and use the class and its members individually. TypeScript privacy offers no protection outside of the IDE. At least in today’s browsers. I’m not making any kind of value judgement here although I suppose it would be nice if the world outside of the TypeScript compiler would honor my private and protected class members and methods. However, it doesn’t and it’s worth knowing that.

We’re living in a transpiled world without a clear agreement about data protection between execution contexts. Fun times abound!

</end>

Paul Galvin

Author and Practice Director @ Neudesic/IBM. Father, Not-Great-But-Always-Trying Zen Buddhist. “Yet Another TypeScript Book” (https://amzn.to/2ABntAX).