Dynami c setter от декоратора - Typescript жалуется на свойство только для чтения - PullRequest
0 голосов
/ 08 января 2020

Рассмотрим следующий код:

function configurable(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.set = (n: number) => {
        target[`_${propertyKey}`] = n * 100;
    };
}

class Test {
    _prop: number = 10;

    @configurable
    get prop(): number {
        return this.prop;
    }
}

const t = new Test();
t.prop = 100;

Это глупый пример, когда я пытаюсь динамически добавить установщик с помощью декоратора, но машинопись пишет, что t.prop будет только для чтения

1 Ответ

1 голос
/ 11 января 2020

Следующий код может помочь вам

function configurable(multiplierFactor: number) { 
    return function (target, propertyKey: string) {
      const privatePropName = `_${propertyKey}`;

      Object.defineProperty(target, propertyKey, {
          configurable: false,
          get: function (this) {
              return this[privatePropName];
          },
          set: function (this, value) {
            this[privatePropName] = value * multiplierFactor;
          },
      });
    }
}

class Test {
    @configurable(10)
    prop: number = 1;
}

const t = new Test();
console.log(t.prop) // 10
t.prop = 20;
console.log(t.prop) // 200
...