Distinct type specification for public field members #54829
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
Right now for a field of a class we can use the modifiers
public
,protected
&private
to control visibility outside of the class, and alsoreadonly
to control whether reassignment is permitted. For encapsulation purposes it is nice to have a field that is publicly accessible however not necessarily modifiable, for example with #-prefix'd fields we can do:Within the class one can use
this.#holds
to get a Set, or externallythis.holds
to get ReadonlySet. It would be nice if the above in-fact had a shorthand that didn't require an accessor specification, e.g.Which is functionally identical to the above (including in terms of inferred typing). The definition would be that:
The public modifier, if with parenthesis-form, is permitted in addition to the private/protected modifiers (both optional) and specifies an alternative type to infer in a public context. If specified without other modifiers the field is presumed private.
🔍 Search Terms
private, modifier, public, access, readonly, fields, members
List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.
✅ Viability Checklist
My suggestion meets these guidelines:
📃 Motivating Example
In order to detect bugs early narrow typing is often desirable to limit mutability of class fields, for example:
For brevity, ease of access, and succinct code, it is quite nice to be able to do
shards.held
in public code to get the list of currently held shards. However doing so also exposes risk, especially in libraries, as doing something simple likeshards.held.add(5)
could have unintended consequences by not respecting the assumptions the rest of the class makes (e.g. changes only occur under the lock).To support this case we support a distinct type for public field access.
💻 Use Cases
Work-around:
Is more lines of code, more verbose, and disconnects the access control from the field definition.
The text was updated successfully, but these errors were encountered: