In EcmaScript/JavaScript classes, you can’t define a property or method as public or private, but luckily there is a proposal to introduce this feature (stage 3, which means a candidate for future ES versions).
In TypeScript, we already have the public
and private
keywords. But now in the recent 3.8 version, TypeScript introduced the EcmaScript private fields already. Let’s find out the differences.
Angular 9
The new version of Angular is just released, but it only supports TypeScript 3.6 and 3.7. So by using 3.8, it would be experimental.
TypeScript private vs EcmaScript #
According to the TypeScript 3.8 announcement we can say these are the main differences:
1 — syntax
// TypeScript
class Person {
private name;
}// EcmaScript proposal / TypeScript 3.8
class Person2 {
#name;
}
A lot of people will probably think behaves the same and that the only difference is syntax. But obviously it isn’t or otherwise, I didn’t write this article. Purely looking at syntax, I think private
looks a lot cleaner than using #
. In every other language which features classes, they use the private
keyword. So it might be a bit strange to see hashtags popping in your code if you used to the traditional keyword.
2 — accessibility
// TypeScript
class Person {
private name = 'Jeroen';
}new Person().name // compile error
new Person()['name'] // works, but not 'really' private// EcmaScript proposal / TypeScript 3.8
class Person2 {
#name = 'Jeroen';
}new Person2().#name // syntax error
new Person2()['#name'] // undefined
So by comparing the above results, you can tell the new #
keyword is private at all times (hard privacy). So this means you can’t reach the property outside its class, only inside use is allowed. The private
keyword isn’t, it just makes it unavailable unless you use the []
brackets (soft privacy).
3 — performance
private
properties and methods are just a fast as public
fields. The #
character might have a slower performance because they are being compiled downlevel to a WeakMap
.
4 — calling
// TypeScript
class Person {
private name = 'Jeroen'; constructor() {
this.name;
}
}// EcmaScript proposal / TypeScript 3.8
class Person2 {
#name = 'Jeroen'; constructor() {
this.#name;
}
}
You probably have seen it in the example of accessibility (2). But to use the property with the #
character, you need to call it with the hashtag: #name
. A pro is that you see immediately if something is private or not. With private
you just call the property like this: name
. Some people prefer to prefix it with an underscore _name
, to make it more visual.
Who wins?
Personally I would say this:
- 1 — syntax
private
keyword - 2 — accessibility
#
character - 3 — performance
private
keyword - 4 — calling
private
keyword
The accessibility of the #
character is just making more sense because of hard privacy, all the other ones are just personal taste.