gpt4 book ai didi

javascript - 在 typescript 中扩展数组原语(angular-cli 项目)

转载 作者:行者123 更新时间:2023-12-04 11:42:25 25 4
gpt4 key购买 nike

我需要能够轻松地对集合进行排序,并且我选择了扩展 Array 原语。我意识到在大多数情况下这被认为是不好的做法,但这只会在内部使用(而不是共享库)。无论我尝试过哪种方法,我都没有得到有效的结果。我不断收到错误:TypeError: Attempted to assign to readonly property .这是我最新迭代的简化示例。我有一个更完整的版本 in the playground所以我假设他的问题在于 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;
});
}
}

}

我也尝试过这种方法,但我的 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) {
...
});
}

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"
]
}

最佳答案

我也遇到了这个问题,所以只需将我的结果粘贴在这里以防有人需要。
在您的 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>;
}
}
然后你可以用这个创建一个文件:
    /** 
* 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'
});
});
};

关于javascript - 在 typescript 中扩展数组原语(angular-cli 项目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42938296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com