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

Nor*_*mal 6 javascript node.js typescript

我在 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)
Run Code Online (Sandbox Code Playgroud)

当我编写代码时Object.groupBy(),出现以下 TypeScript 错误:

Property 'groupBy' does not exist on type 'ObjectConstructor'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

我有以下 TypeScript 配置:

Property 'groupBy' does not exist on type 'ObjectConstructor'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

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

Phi*_*nin 8

以下是启用它的 PR: https: //github.com/microsoft/TypeScript/pull/56805。目前处于打开状态。希望很快就能合并。

在合并之前,您可以使用解决方法在项目中添加这些扩展接口:

/// {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');
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你;这对我来说可以。我看到 PR 已合并到 5.4 的下一个 TS 版本中。希望我们能在那里看到它。 (2认同)