-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Readonly methods and readonly types #61690
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
Comments
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Well, your second link is not a duplicate, there is another topic, although its name is the same as mine, but the meaning is completely different (there, readonly means just preventing the replacement of a method by another) And the first link suggests a similar meaning, but a different syntax, not very suitable for TS. But okay, we can continue there. |
True. My mistake, didn't look properly enough.
Different syntax suggestion is not enough reason for a new issue. The problem that should be solved matters. |
π Search Terms
readonly methods
β Viability Checklist
β Suggestion
I suggest using the readonly keyword for methods, indicating that they don't change the contents of the "this" object, but only receive data. Similar to const methods in C++. This will provide good security from possible errors, as well as better understanding of the code:
And the types themselves can also be marked as readonly, meaning that all their contents become readonly, and only readonly methods are available:
We already have such syntax for declaring readonly arrays. And it will become a universal declaration for any readonly objects.
And if the method does not change the contents of the class, but returns a reference to some internal object of the class, then we can overload the signature of this method in two versions (with and without readonly):
It is also necessary to clarify that the readonly type means deep readonly of the entire nested structure of the object, not just the first-level properties. And if we need a different behavior for individual properties, we can overload the getters for them, just like in the example above.
As an additional option, we can use readonly for the declared interface or class as a whole, eliminating the need to write it for each method:
π Motivating Example
π» Use Cases
As I mentioned above, this concept is implemented in C++, but using the const keyword:
It is also partially implemented in C#, but in a very limited version. I don't see any reason why it couldn't be fully implemented.
In TypeScript as an alternative we can try to wrap "this" in some kind of typing:
but I haven't found the right implementation of this wrapper yet. And anyway, it's very cumbersome to write it like that for all methods, especially in template classes.
The text was updated successfully, but these errors were encountered: