-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Class property readonly?
for external consumers
#53707
Comments
I'm like 99% sure this is a dupe but I can't seem to find the other issue now. For the record though, option 2 (runtime enforcement) is untenable:
Emitting different code based on the presence of |
Duplicate of #37487. |
@MartinJohns How did you find that? I was certain that issue existed but I tried searching for various permutations of |
@fatcerberus I searched for |
Closing it as it is a duplicate of #37487 |
Suggestion
Add ability to specify that some class property is read-only for users outside the class, but it should still be writable by the code within the class.
This behaviour can be achieved with getters and setter, but: (1) it is very verbose; (2) and there is performance penalty.
Instead, would be nice if this behaviour could be achieved with a single line of code:
Note
?
inreadonly?
. The?
could indicate a new flavor ofreadonly
keyword, which makes the property read-only for external users, but still writable for code inside the class.✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
I see there could be two implementation approaches.
Option 1: No runtime changes, only type checking
Here the compiler would emit the same JavaScript code as if the
readonly?
keyword was not present. The only difference would be errors in TypeScript, if somebody tries to modify the property from outside the class.Option 2: Enforcing it
TypeScript could rewrite the property to enforce it being read-only from outside the class, but still writable from within the class.
This TypeScript code:
Would result in JavaScript like this:
💻 Use Cases
Consider this controllable
Promise
class—Defer
, to avoid getter/setter performance penalty and still have TypeScript'sreadonly
annotation, one needs to castthis
toany
.With the proposed change, the code would change to
The text was updated successfully, but these errors were encountered: