Typescript Classes 10 exercises

Prevent Access to Private Properties in Classes

As mentioned in the introduction to this exercise, there are two ways to prevent access to private properties in classes.

Let's start by looking at the TypeScript-first approach.

TypeScript-First Approach

This approach introduces the private keyword to describe the attributes:

Loading solution


00:00 Let's look at the TypeScript first way first. The TypeScript first way basically introduces a new keyword into TypeScript or into JavaScript to describe these attributes. And we can say private X and private Y. These aren't people in the army.

00:18 This is describing whether this is a public property or a private property. If I wanted this to be public, I could just say public Y and public is the default too. So we get private X and private Y. And now when we try to access them from the outside, you can see that it is private and can only be accessible within class CanvasNode.

00:39 That's pretty cool. But this is like a TypeScript only thing. This means if we ever need to refactor our code to JavaScript, like it would be great if this worked at runtime. It turns out there is a language feature we can use for this too, which is to add a and what is this a hash? God, I lost my brain for a second there.

00:58 A hash in front of X and Y. And now this means that you, without needing to add any separate annotations, by just using this hash inside a class, you can see that we get this dot hash X equals position this. And it means now that we can't access, we can't access X on this, of course,

01:17 but we also can't access hash X either. So property hash X is not accessible outside class CanvasNode because it has a private identifier. So that hash is a private identifier. Super nice. So I would always recommend choosing the JavaScript first way of doing things.

01:36 And so this, I think, is the correct solution for us, meaning that we can actually just use a JavaScript like built in syntax, which is like part of how browsers and how the language works, essentially, and not relying on a TypeScript only syntax for this.