You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let classes declare properties with separate public and private types.
π Motivating Example
classStack<T>{// privately, the property is mutableprivatedata: T[]=[];// publicly, the property is immutable.publicreadonlydata: readonlyT[];push(item: T){// private type is mutablethis.data.push(item);}}stack.data.push("foo")// Not allowed; public type is immutable
Current alternatives are verbose and/or have limitations:
Type assertion:
classStack<T>{publicreadonlydata: readonlyT[];push(item: T){(this.dataasT[]).push(item);}// manually asset type every time inside class body}
Multiple properties:
classStack<T>{readonly #data: T[]=[];// cannot be re-assignedreadonlydata=this.#data asreadonlyT[];// use private property #data inside class body}
Accessors:
classStack<T>{
#data: T[]=[];getdata(){returnthis.#data asreadonlyT[];}// use private property #data inside class body}
π» Use Cases
Prevent re-assignment from outside the class body.
Export a live array/set/map but prevent mutation from outside the class body.
Export superclass properties but use subclass-methods internally.
The text was updated successfully, but these errors were encountered:
Suggestion
π Search Terms
Separate public and private type
Privately typed properties
Public and private types
Supertype properties
Subtype properties
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
Let classes declare properties with separate public and private types.
π Motivating Example
Current alternatives are verbose and/or have limitations:
Type assertion:
Multiple properties:
Accessors:
π» Use Cases
Prevent re-assignment from outside the class body.
Export a live array/set/map but prevent mutation from outside the class body.
Export superclass properties but use subclass-methods internally.
The text was updated successfully, but these errors were encountered: