In Typescript, I often find myself writing this sort of getter/setter boilerplate:
private _length = 0;
get length(): number { return this._length; }
set length(value: number) { this._length = value; }
In C#, I know that you can write something like this:
public length { get; set; }
Is there an equivalent way to simplify my Typescript code?
One way that I've found is to use decorators, which were introduced in Typescript 1.5. The implementation looks like this:
function prop(target: Object, name: string) {
Object.defineProperty(target, name, {
get: function() { return this["_" + name]; },
set: function(value) { this["_" + name] = value; },
enumerable: true,
configurable: true
});
}
Now, you can replace the code in the OP with this:
@prop length = 0;
One thing to note is that a _length property will be added to the object. If you don't need to access it, you're good! If you do need to use it, and you want it to autocomplete, you can annotate the property like so:
@prop length = 0; private _length = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With