javascript 如何在TypeScript和Node.js中启用Object.groupBy()

hwazgwia  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(63)

我在Node.js v18.17.1和TypeScript v5上运行。
我听说了新的JavaScript方法Object.groupBy()

const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];

const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result)

字符串
当我写Object.groupBy()代码时,我得到了下面的TypeScript错误:

Property 'groupBy' does not exist on type 'ObjectConstructor'.ts(2339)


我有以下TypeScript配置:

"compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    // ... etc


如何启用Object.groupBy()以便在代码中使用它?

wa7juj8i

wa7juj8i1#

下面是启用它的PR:https://github.com/microsoft/TypeScript/pull/56805。它目前处于Open状态。希望很快会合并。
在合并之前,您可以使用一个解决方案在项目中添加这些扩展接口:

/// {projectSrcRoot}/groupBy.d.ts

interface ObjectConstructor {
    /**
     * Groups members of an iterable according to the return value of the passed callback.
     * @param items An iterable.
     * @param keySelector A callback which will be invoked for each item in items.
     */
    groupBy<K extends PropertyKey, T>(
        items: Iterable<T>,
        keySelector: (item: T, index: number) => K,
    ): Partial<Record<K, T[]>>;
}

interface MapConstructor {
    /**
     * Groups members of an iterable according to the return value of the passed callback.
     * @param items An iterable.
     * @param keySelector A callback which will be invoked for each item in items.
     */
    groupBy<K, T>(
        items: Iterable<T>,
        keySelector: (item: T, index: number) => K,
    ): Map<K, T[]>;
}

const basic = Object.groupBy([0, 2, 8], x => x < 5 ? 'small' : 'large');

字符串

相关问题