Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing getter/setter boilerplate in Typescript

Tags:

typescript

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?

like image 273
thedayturns Avatar asked Nov 28 '25 01:11

thedayturns


1 Answers

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;
like image 96
thedayturns Avatar answered Nov 29 '25 16:11

thedayturns