0

how in angular *.ts files i can call somethins like this:

const a = {a: 1};
a.get('a'); // return 1

trying to do something like below, but always error in compiler or console

Object.defineProperties(Object.prototype, {
  get: {
    value: (key: string, defaultValue = null) => {
      console.log(this);
      if (!this || !key) {
        return defaultValue;
      }
      const keyArr = key.split('.');
      const itemKey = keyArr.shift();
      let result = this[ itemKey ];

      if (result === undefined) {
        if (this instanceof Array && isNaN(+itemKey)) {
          const resultArr = Array.from(this.keys())
            .map((k: any) => {
              keyArr.unshift(k, itemKey);
              return this.get(keyArr.join('.'));
            })
            .filter(res => res !== null);
          return resultArr.length ? resultArr : defaultValue;
        }
        result = defaultValue;
      }
      return result && keyArr.length ? this.get(keyArr.join('.'), defaultValue) : result;
    },
    enumerable: false,
    configurable: false,
    writable: true
  }
});

errors:

ERROR in src/app/app.component.ts(15,24): error TS2339: Property 'get' does not exist on type 'Object'.

Invalid property descriptor. Cannot both specify accessors and a value or writable attribute

2 Answers2

0

Since you are augmenting built-in JS prototypes (which, BTW, it often considered a bad practice), you need to augment the global API declarations. You can do this by adding get() to the global Object interface:

// in a file like `global.d.ts` (which has no module import/export statements)
declare interface Object {
  get(key: string): any;
}
Aaron Beall
  • 49,769
  • 26
  • 85
  • 103
0

in angular case problem was with define property "get" and "get" method... rename my property to "$get" and now it is work.

.../src/global.ts

declare interface Object {
  $get(item: any, key: string, defaultValue?): any;
}

Object.defineProperties(Object.prototype, {
  $get: {
    value: (item: any, key: string, defaultValue = null): any => {
      console.log(this);
      if (!item || !key) {
        return defaultValue;
      }
      const keyArr = key.split('.');
      const itemKey = keyArr.shift();
      let result = item[itemKey];
      if (result === undefined) {
        if (item instanceof Array && isNaN(+itemKey)) {
          const resultArr = Array.from(item.keys())
            .map((k: any) => {
              keyArr.unshift(k, itemKey);
              return item.$get(item, keyArr.join('.'));
            })
            .filter(res => res !== null);
          return resultArr.length ? resultArr : defaultValue;
        }
        result = defaultValue;
      }
      return result && keyArr.length ? item.$get(result, keyArr.join('.'), defaultValue) : result;
    },
    enumerable: false,
    configurable: false,
    writable: true
  }
});

and add import './global'; to .../src/main.ts file