Extending array primitive in typescript (angular-cli project)

I needed the ability to easily sort collections, and I decided to extend the Array primitive. I understand this is considered bad practice in most cases, but this will only be used internally (not for a shared library). No matter which approach I try, I am not getting a working result. I keep getting an error: TypeError: Attempted to assign to readonly property

. This is a simplified example of my last iteration. I have a more complete version of this working in the playground , so I'm guessing the problem is with the angular-cli config / build process ???

interface Array<T> {
  $sortBy(sortKey:string): T[];
}

if (!Array.prototype['$sortBy']) {

  Object.defineProperty(Array.prototype, '$sortBy', {
    value: function(sortKey) {
      return this.sort( function(a, b) { // TypeError here???
        if (a[sortKey] < b[sortKey]) { return -1; }
        if (a[sortKey] > b[sortKey]) { return 1; }
        return 0;
      });
    }
  }

}

      

I have also tried this approach, but my IDE (VSCode) is giving me an error: [ts] Property '$sortBy' does not exist on type 'any[]'.

         Intellisense error here
                   |
                   V
Array.prototype.$sortBy = function(sortKey:string){
  return this.sort( function(a, b) {
    ...
  });
}

      

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "lib": [
      "es2016"
    ]
  }
}

      

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
  "lib": [
    "es2016",
    "dom"
  ],
    "outDir": "../out-tsc/app",
    "target": "es5",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

      

+3
javascript extend angular typescript angular-cli


source to share


No one has answered this question yet

See similar questions:

23
How to extend JavaScript native array in TypeScript
3
Class extended from built-in array in Typescript 1.6.2 does not update length when using the [] operator

or similar:

871
How to extend an existing JavaScript array with another array without creating a new array
563
Huge amount of files generated for each Angular project
240
How to add font-awesome to Angular 2 + CLI project
209
How to add upload to angular-cli project
164
Angular CLI SASS Options
2
Unknown compiler option 'angularCompilerOptions' in angular assembly 2x forward
1
Got "TS2300: Repeat ID" Account "after upgrade to" Typewriter "2.9.1
0
Import operation was not compiled if not used later
0
angular 2 npm error starting duplicate ids
0
Angular jasmine problem in VS Code



All Articles
Loading...
X
Show
Funny
Dev
Pics