Typescript property of readonly class

I noticed that typescript 2.0 will support the readonly properties of the class, but it is not yet available. The reason for this post is that I want to be smart about how I write my code today, so that then I can go with minimal pain.

I want to use a class with readonly properties this way:

let widget = new Widget(110, 220); // width, height //... widget.width(200); // to modify the width, I use a setter with validation widget.width = 300; // note: I want this to be a compile time error //... let w = widget.width; // and later I want to get/draw the current width 

... but I can't get this to work because fn and the property have the same name, so I will switch the name fn to setWidth. I would prefer not to prefix all my readonly properties with _, because in the past I have found that pain is more than just the hassle of adding an extra character. And because of the TS type check, I don't need a visual reminder that the property is readonly (or private).

Q1: Will the above work work in typescript 2 if the width is the readonly property of the widget class, as shown below?

 export class widget { readonly width:number; // doesn't work in TS 1.8 setWidth(w:number) { this.width = w; } } 

In the short term, I can either make the property publicly available so that I can access it directly with a β€œrisk” that could set the property directly, or I can have private properties and write getters and setters.

Q2: If I do the latter, how much slower will the getter be than a direct link? Some of my properties will be called very often when dragging, so speed is important.

 widget.getWidth(); // vs widget.width; 

UPDATE

I recently found this posted answer and realized that TS already supports most of what I was trying to do:

 export class Widget { private _width:number; set width(w) {if (w >= 0) this._width = w} get width() {return this._width} } 

The usage syntax is the same as for a public object without access, which is really different:

 let widget = new Widget(...); let existingWidth = widget.width; widget.width = newWidth; 

I hope that the TS2 readonly qualifier will give me direct access to access to (private) properties (not through the access function, it’s faster), and none of my usage rules need to be changed. Somebody knows?

+6
source share
1 answer

Now that I am using TS2, I find that readonly is not what I want, because the read-only restriction applies even inside the class. Therefore, the best I can think of is to use a private modifier and write an explicit getter method. This is unfortunate for two reasons: read speed (presumably), and the getter method name must be different from the name of the private variable.

+6
source

All Articles