Now is the best moment to implement protected fields in classes

The ECMAScript 2022 brought support to private fields in classes using # but still without support to protected fields (still acessible internaly in subclasses but not externaly). This resource can be very useful and already is implemented (declaration only) in typescript.

1 Like

That's because, as has been discussed extensively on other threads, "protected" doesn't make any sense in JS. JS doesn't have "access levels", it has "reachability" - things are either reachable or aren't.

I'd recommend searching this discourse for other discussions on the subject.

3 Likes

One of those thread where it is postulated that there may be a way to implement protected like semantics: A simple way to implement protected

Thanks for the tip, but for very large classes it is not feasible to do all this manually, a native resource would be very useful in these cases. If you see the typescript, it already implements this feature in the typing which shows that there is a use for it

No, it shows that there's an expectation that "access levels" from other languages should work in JS - but the existence of an expectation isn't the same thing as the expectation being reasonable.

From what I recall it's mostly a matter of defining the right helpers and/or decorators.

Instead of thinking in terms of "access levels" (a hill you're willing to die on to prevent), try thinking in terms of an opt-in mechanism for seamlessly sharing private fields with descendants. That's what I think most of us want when we ask for "protected fields". It's not even necessary for it to be called "protected" if the concept rubs you the wrong way so harshly. All we really want is the functionality. Since it can be done in runtime logic with ES as it currently stands, there shouldn't be any logical issue with providing it. If there is, I'd like to know what that is.