在打字稿中扩展数组原语(angular-cli 项目)

Bri*_*ian 5 javascript extend typescript angular-cli angular

我需要能够轻松对集合进行排序,并且我选择扩展 Array 原语。我意识到在大多数情况下这被认为是不好的做法,但这只会在内部使用(不是共享库)。无论我尝试过什么方法,我都没有得到有效的结果。我不断收到错误:TypeError: Attempted to assign to readonly property。这是我最近一次迭代的简化示例。我在操场上有一个更完整的版本,所以我假设他的问题在于 angular-cli 配置/构建过程???

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

}
Run Code Online (Sandbox Code Playgroud)

我也试过这种方法,但我的 IDE (VSCode) 给了我错误: [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) {
    ...
  });
}
Run Code Online (Sandbox Code Playgroud)

配置文件

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

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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

loo*_*nix 1

我也遇到了这个问题,所以将我的结果粘贴在这里,以防有人需要。

在你的main.ts文件中添加以下内容:

// Here will be all extension methods that will be shared globally across the app
declare global {
  interface Array<T> {
    sortAlphaNumeric(fieldName: string): Array<T>;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用这个创建一个文件:

    /** 
     * The extension of Array type allows to sort AlphaNumeric data
     * @param fieldName {string} requires the field name which you want to sort by
     */
    Array.prototype.sortAlphaNumeric = function (fieldName: string) {
        return this.sort((a, b) => {
            return a[fieldName].toLowerCase().localeCompare(b[fieldName].toLowerCase(), undefined, {
                numeric: true,
                sensitivity: 'base'
            });
        });
    };
Run Code Online (Sandbox Code Playgroud)