What are private keywords vs private fields in TypeScript?

Both the private keyword and private field are used to protect member variables in a class. In this shot, we will go through the differences between them.

Private keyword

The private keyword is provided by TypeScript to give compile-time protection.

In the following example, we created a class, User, which has a member variable id, for which we provided the private keyword. It tells the compiler that the id property can only be accessed in the User class.

The compiler will throw the error Property 'id' is private and only accessible within class 'User' for the following code snippet, since we access the private member variable from outside the class in line 6.

class User{
//declaring variable as private with private keyword
private id = 1;
}
const user1 = new User();
//accessing private variable
console.log(user1.id);

The problem with this is that the private keyword doesn’t exist in JavaScript, so it doesn’t provide runtime protection.

We can easily bypass compile-time protection with typecasting.

In the following code snippet, we access and print the variable that is protected by the private keyword by typecasting user1 as any type.

class User{
//declaring variable as private with private keyword
private id = 1;
}
const user1 = new User();
//accessing private variable
console.log((user1 as any).id);

Private field

The private field is newly added in JavaScript, and can also be used in TypeScript.

  • It provides runtime protection, as it is also available in JavaScript.
  • We can declare a member as a private field by providing # before the variable.
#id = 1;

In the following code snippet, we try to access a private field #id from outside the class User. It will throw the error Property '#id' is not accessible outside class 'User' because it has a private identifier.

Note: If the following code snippet doesn’t throw the above-mentioned error, please try the code in the typescripthttps://www.typescriptlang.org/play/.

class User{
//declaring variable as private with private field
#id = 1;
}
const user1 = new User();
//accessing private variable
console.log(user1.#id);

We cannot bypass it with typecasting, as it is also protected at runtime.

Free Resources