Be Kind
Be Kind

Reputation: 5182

Is there a way to generate getter and setter pairs in typescript class?

I have many blocks of code, which are quite similar and look like this:

// BLOCK 1
get computed1() {
  return this.dataComputed1;
}
set computed1(value: any) {
  update(value);
}

// BLOCK 2
get computed2() {
  return this.dataComputed2;
}
set computed2(value: any) {
  update(value);
}

...

Now, seeing that "BLOCK 1" and "BLOCK 2" are quite similar (taken out of context and if we look at it as a text of course). I'm wondering if there's a way to transform this code by introducing some kind of code generator (similar to scss mixins):

// BLOCK 1
makeComputed('computed1');

// BLOCK 2
makeComputed('computed2');

...

Upvotes: 0

Views: 1016

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 37948

Below is an example of defining getters and setters using Object.defineProperty

class Foo {
}

function makeComputed(prop) {
    const field = `data${prop}`;
    Object.defineProperty(Foo.prototype, prop, {
        get: function () {
            console.log(`getting ${field}`);
            return this[field];
        },
        set: function (value) {
            console.log(`updating ${field}`);
            this[field] = value;
        },
        enumerable: true,
        configurable: true
    });
}

makeComputed('computed1');
makeComputed('computed2');

const foo = new Foo();

foo.computed1 = 123;
console.log(foo.computed1);

Pay attention - accessing such a properties (last two lines) will cause an error in Typescript, because it has no idea that Foo now has computed1 and computed2 props.

Upvotes: 1

Danyal Imran
Danyal Imran

Reputation: 2605

There isn't any easy shortcut solution to your problem you'll need to handle each request via an if/else or switch statement

function makeComputer(op) {
  switch (op) {
    case 'computed1':
      // logic
      break;
    case 'computer2':
      // logic
      break;
    default:
      // logic
  }
}

A good pattern I picked up was called the 'parm' from Microsoft Dynamics. This has combined getter setter in them, combined with the above approach you will be able to handle get/set and operation look up in one single function.

function parmX(x) {
  if (x) this.x = x;
  else return this.x;
}

Upvotes: 0

Related Questions