首页 > 解决方案 > 如何在 Typescript 中使用代理为新属性添加 getter

问题描述

我有一个对象,我想向其中添加一个新属性:

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.

我应该怎么办?

标签: angulartypescriptproxy-pattern

解决方案


正如下车我的草坪所建议的,这可以解决

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)
  },

推荐阅读