Learn TypeScript

Using access modifiers

Using access modifiers

In this lesson, we'll learn the different access modifiers available to class members and how to implement them.

Public members

We are going to explore access modifiers in classes in an exercise.

TypeScriptOpen exercise in CodeSandbox

The code contains the Product class we worked on in the last lesson, along with instances of this class in variables table1 and table2.

  • Let's try to access and change the price field outside the class definition, in the consuming code:
table1.price = 100;
🤔

Are any errors raised on this assignment?

Class members are public by default, which means consuming code can access them.

Readonly fields

We can make fields readonly using a readonly modifier before the field name:

readonly readonlyField: TypeName;
  • Make the price field readonly so that the table1.price = 100; raises a type error.

Private members

We must use the private keyword in front of a class member to make it private and not accessible by consuming code.

  • Remove the readonly keyword from the price field.

  • Make the name and price fields private.

🤔

Is the table1.price = 100 assignment raising an error now?

  • Output table1 to the console after the table1.price = 100 assignment:
console.log(table1);
🤔

Is the table1.price actually changed, or does the private keyword prevent this from happening? Have a look in the console to find out.

TypeScript access modifiers don't take any effect on the code at runtime.

Private members in JavaScript

Recent versions of JavaScript support private fields that do take effect at runtime. However, the syntax is different to TypeScript. Instead of using the private keyword, the hash (#) symbol is used.

So, our example could use JavaScript private fields as follows:

#name: string;
#price: number;

Unfortunately, our code editor doesn't support this syntax yet. You can experiment with JavaScript private fields in the TypeScript playground.

Protected members

The final access modifier is protected.

🤔

What do you think the protected access modifier does?

Constructor assignment

There is TypeScript syntax that allows us to create and initialize fields in a constructor concisely.

constructor(accessModifier fieldName1: type1, accessModifier fieldName2: type2, ...) { }

Use this syntax and refactor the name and price fields in the the Product class to make the implementation more concise:

Neat!

Summary

We can enforce class member access using the public, private, and protected accessors. It is important to be aware that it is TypeScript enforcing this access at development time and not at runtime.

Next, we will learn how to enforce the structure of a class with an interface.

Did you find this lesson useful?

Share this lesson on twitter
© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more