Create Private Class Fields Using TypeScript's private Modifier

Share this video with your friends

Send Tweet

In this lesson, we're going over how to create private class fields using TypeScript's private modifier. However, as we're going to see, the private modifier doesn't give us any actual protection at runtime; it only exists in TypeScript's type system and is completely compiled away when emitting JavaScript code.

Sijan Shrestha
Sijan Shrestha
~ 2 years ago

The issue with the private modifier counter["count"] = 25 seems to be resolved now by typescript? When I run it, I am not allowed to compile, is this because of some default flags or an improvement to the typescript?

Marius Schulz
Marius Schulz(instructor)
~ 2 years ago

@Sijan: The TypeScript compiler will give you a type error when you try to access a class field with a private modifier outside of that class. However that check is only a compile-time type check. There's no runtime enforcement whatsoever; that is, the private modifier is completely compiled away and the field access will succeed when the JavaScript code gets executed.