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
Instructor: [0:00] In this lesson, I want to compare and contrast different ways for working with class fields in TypeScript. Let's have a look at this counter class. It defines a field called value, and it exposes a method for incrementing the current value as well as a getter for retrieving the current value. I'm going to create an instance of the counter class. I'm also going to call the increment() method a bunch of times.
[0:29] Now that we've incremented the counter a bunch of times, let's go ahead and log the current value to the console. I'm going to open the terminal. First up, we're going to compile our project, and then I'm going to execute the index.js file in Node. As you can see, we're getting the value 3 because we've incremented the counter three times. So far, so good.
[1:10] Even outside of the counter class, I can access the value field, and TypeScript even suggests it to me in the autocompletion list here. If we wanted to assign a completely non-sensical value here, we could. What can we do to prevent assignments like these?
[1:27] One thing we can do is to add TypeScript's private modifier to the field declaration. Now we're getting a TypeError in line 18. TypeScript is telling us that the property value is private and that we can only access it from within the class counter.
[1:42] The TypeScript compiler will now warn us about inappropriate usages of the value prop, but it won't prevent inappropriate usages at runtime. The private modifier doesn't give us any actual protection.
[1:54] It's very easy for someone to get around this TypeError. For example, someone could simply add a @ts-ignore comment in the line above, and now the TypeError goes away.
[2:05] Alternatively, you can also use the index notation to access the value field. As you can see, TypeScript even suggests it here. This is kind of an escape hatch by the compiler. We can access the field with a private modifier outside of the class it is declared in. If I now run the program again, you can see that the private modifier didn't give us any protection at runtime.
[2:50] The most important thing to remember is that the private modifier does not give us any privacy at runtime.
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?
@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