TS 5.4:Object.groupBy 和 Map.groupBy 方法添加了类型声明

2024年 3月 4日 78.4k 0

2 月 22 日,TypeScript 团队发布了 TypeScript 5.4 RC 版本。即将发布的 TypeScript 5.4 为 Object.groupBy 和 Map.groupBy 方法添加了类型声明。

通过以下命令,你就可以体验最新的 TypeScript 5.4 RC 版本:

npm install -D typescript@rc

本文我将介绍 Object.groupBy 和 Map.groupBy 这两个方法,需要注意的是,你需要把 tsconfig.json 文件中 target 属性配置成 esnext 才访问这些方法。

{
  "compilerOptions": {
    "target": "esnext", 
  }
}

Object.groupBy()

Object.groupBy() 静态方法会根据提供的回调函数返回的字符串值对给定可迭代的元素进行分组。该方法的类型定义如下:

// typescript/lib/lib.esnext.object.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(
        items: Iterable,
        keySelector: (item: T, index: number) => K,
    ): Partial;
}

在以上代码中,K 和 T 是泛型变量,其中 K extends PropertyKey 是泛型约束,PropertyKey 是一个联合类型:

type PropertyKey = string | number | symbol;

而 Partial 和 Record 是 TypeScript 内置的工具类型。由 groupBy 的类型定义可知,参数 keySelector 是函数类型,包含 item 和 index 两个参数。

下面,我们将使用 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 groupedByType = Object.groupBy(inventory, ({ type }) => type);

Map.groupBy()

Map.groupBy() 静态方法使用提供的回调函数返回的值对给定可迭代的元素进行分组。最终返回的 Map 使用测试函数中的唯一值作为键,可用于获取每个组中的元素数组。该方法的类型定义如下:

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(
        items: Iterable,
        keySelector: (item: T, index: number) => K,
    ): Map;
}

在以上代码中,K 和 T 是泛型变量。调用该方法后,会返回 Map 类型的对象。与 Object.groupBy 静态方法一样,参数 keySelector 也是函数类型,包含 item 和 index 两个参数。

下面我们来看一下如何使用 Map.groupBy() 方法对数组中的对象进行分组:

const inventory = [
  { name: 'asparagus', type: 'vegetables', quantity: 6 },
  { name: 'bananas', type: 'fruit', quantity: 16 },
  { name: 'goat', type: 'meat', quantity: 20 },
  { name: 'cherries', type: 'fruit', quantity: 12 },
  { name: 'fish', type: 'meat', quantity: 8 },
];

const result = Map.groupBy(inventory, ({ quantity }) =>
  quantity < 10 ? "restock" : "sufficient",
);

const restock = result.get("restock");
const sufficient = result.get("sufficient");

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论