简体   繁体   中英

How to add a getter for a new property with a Proxy in Typescript

I have an object that I'd like to add a new property to:

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

I'm using this in an angular application, and currently have a exampleConfig.myProperty . I'd like to add a exampleConfig.myExtendedProperty

I tried

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

However, the compiler throws:

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.

What should I do?

As suggested by Get Off My Lawn, this can be solved with

return Reflect.get(obj, prop, receiver)

so in this case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM