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
{{ message }}
Repository navigation
Declare properties with a separate public and private types.Β #51597
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.
Activity
MartinJohns commentedon Nov 19, 2022
Duplicate of #37487.
TheCymaera commentedon Nov 19, 2022
There are similar use cases but this is not a duplicate.
That suggestion does not permit using subtypes, such as making the array immutable like in my example.
MartinJohns commentedon Nov 19, 2022
It's in the comments.
TheCymaera commentedon Nov 19, 2022
Ah, I see.