【问题标题】:How to add a getter for a new property with a Proxy in Typescript如何在 Typescript 中使用代理为新属性添加 getter
【发布时间】:2021-09-14 16:40:22
【问题描述】:

我有一个想要添加新属性的对象:

this.exampleConfig = new Proxy(config, {
    set: (obj, prop, value) => {
        ...
    }
}

我在 Angular 应用程序中使用它,目前有一个 exampleConfig.myProperty。我想加一个exampleConfig.myExtendedProperty

我试过了

this.fileConfig = new Proxy(config, {
  set: (obj, prop, value) => {
      ...
  },
  get: function (obj, prop, receiver) {
    if (prop === "myExtendedProperty") {
      return obj.myProperty.toUpperCase()+'_EXTENSION';
    }
    return Reflect.get(...arguments);
  },
});

但是,编译器会抛出:

Error ...  : Expected 2-3 arguments, but got 0 or more.  
  return Reflect.get(...arguments);

node_modules/typescript/lib/lib.es2015.reflect.d.ts:26:18
    26     function get(target: object, propertyKey: PropertyKey, receiver?: any): any;
                        ~~~~~~~~~~~~~~
    An argument for 'target' was not provided.

我该怎么办?

【问题讨论】:

  • 你试过return Reflect.get(obj, prop, receiver)
  • 成功了!您想将其作为答案,我会将其标记为已接受吗?

标签: angular typescript proxy-pattern


【解决方案1】:

根据 Get Off My Lawn 的建议, 这可以解决

return Reflect.get(obj, prop, receiver)

在这种情况下

get: function (obj, prop, receiver) {
    if (prop === "myExtendedProperty") {
      return obj.myProperty.toUpperCase()+'_EXTENSION';
    }
    return Reflect.get(obj, prop, receiver)
  },

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 2018-12-05
    • 2020-11-28
    • 2020-12-12
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多