首页 > web前端 > js教程 > 正文

使用 TypeScript 实现类型安全的 Group By 和 Sum 操作

聖光之護
发布: 2025-08-17 21:48:01
原创
572人浏览过

使用 typescript 实现类型安全的 group by 和 sum 操作

本文介绍如何使用 TypeScript 实现一个通用的、类型安全的 groupBySum 函数,该函数可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。该函数不仅具备通用性,而且利用 TypeScript 的类型系统,提供了编译时的类型检查,确保代码的健壮性和可维护性。

groupBySum 函数的实现

以下是 groupBySum 函数的 TypeScript 实现:

/**
 * Sums object value(s) in an array of objects, grouping by arbitrary object keys.
 *
 * @remarks
 * This method takes and returns an array of objects.
 * The resulting array of object contains a subset of the object keys in the
 * original array.
 *
 * @param arr - The array of objects to group by and sum.
 * @param groupByKeys - An array with the keys to group by.
 * @param sumKeys - An array with the keys to sum. The keys must refer
 *    to numeric values.
 * @returns An array of objects, grouped by groupByKeys and with the values
 *    of keys in sumKeys summed up.
 */
const groupBySum = <T, K extends keyof T, S extends keyof T>(
  arr: T[],
  groupByKeys: K[],
  sumKeys: S[]
): Pick<T, K | S>[] => {
  return [
    ...arr
      .reduce((accu, curr) => {
        const keyArr = groupByKeys.map((key) => curr[key]);
        const key = keyArr.join("-");
        const groupedSum =
          accu.get(key) ||
          Object.assign(
            {},
            Object.fromEntries(groupByKeys.map((key) => [key, curr[key]])),
            Object.fromEntries(sumKeys.map((key) => [key, 0]))
          );
        for (let key of sumKeys) {
          groupedSum[key] += curr[key];
        }
        return accu.set(key, groupedSum);
      }, new Map())
      .values(),
  ];
};
登录后复制

代码解释:

  1. 泛型定义: groupBySum 函数使用了三个泛型类型:T 代表输入数组中对象的类型,K 代表用于分组的键的类型,S 代表用于求和的键的类型。K 和 S 都被约束为 keyof T,这意味着它们必须是 T 类型对象中存在的键。

  2. 参数:

    • arr: 要进行分组和求和的对象数组。
    • groupByKeys: 一个字符串数组,包含用于分组的键。
    • sumKeys: 一个字符串数组,包含用于求和的键。
  3. reduce 方法: 使用 reduce 方法遍历输入数组 arr。reduce 方法的第一个参数是一个累加器函数,它接收两个参数:

    • accu: 累加器,这里是一个 Map 对象,用于存储分组后的结果。键是根据 groupByKeys 生成的字符串,值是分组后的对象。
    • curr: 当前正在处理的数组元素。
  4. 生成分组键: 使用 groupByKeys.map((key) => curr[key]) 从当前对象 curr 中提取用于分组的键的值,并将它们连接成一个字符串作为分组键。

  5. 创建或更新分组对象:

    • accu.get(key) || ...: 尝试从累加器 accu 中获取与当前分组键对应的对象。如果不存在,则创建一个新的对象。
    • Object.assign(...): 如果分组键不存在,则使用 Object.assign 创建一个新的对象,该对象包含:
      • 从 groupByKeys 中提取的键值对
      • 从 sumKeys 中提取的键,其初始值为 0。
  6. 累加求和: 遍历 sumKeys 数组,将当前对象 curr 中对应键的值累加到分组对象中。

    寻鲸AI
    寻鲸AI

    寻鲸AI是一款功能强大的人工智能写作工具,支持对话提问、内置多场景写作模板如写作辅助类、营销推广类等,更能一键写作各类策划方案。

    寻鲸AI 68
    查看详情 寻鲸AI
  7. 返回结果: 将累加器 accu 中的所有值提取到一个新的数组中,并返回该数组。

  8. 类型安全: 函数的返回类型 Pick<T, K | S>[] 确保返回的数组中的对象只包含用于分组的键 K 和用于求和的键 S。

使用示例

以下是一些使用 groupBySum 函数的示例:

const arr = [
  { shape: "square", color: "red", available: 1, ordered: 1 },
  { shape: "square", color: "red", available: 2, ordered: 1 },
  { shape: "circle", color: "blue", available: 0, ordered: 3 },
  { shape: "square", color: "blue", available: 4, ordered: 4 },
];

// Group by "shape" and sum "available"
const result1 = groupBySum(arr, ["shape"], ["available"]);
console.log('groupBySum(arr, ["shape"], ["available"])')
console.log(result1);
// Output:
// [
//   { shape: "square", available: 7 },
//   { shape: "circle", available: 0 }
// ]

// Group by "color" and sum "ordered"
const result2 = groupBySum(arr, ["color"], ["ordered"]);
console.log('\n\ngroupBySum(arr, ["color"], ["ordered"])')
console.log(result2);
// Output:
// [
//   { color: "red", ordered: 2 },
//   { color: "blue", ordered: 7 }
// ]

// Group by "shape" and "color" and sum "available" and "ordered"
const result3 = groupBySum(arr, ["shape", "color"], ["available", "ordered"]);
console.log('\n\ngroupBySum(arr, ["shape", "color"], ["available", "ordered"])')
console.log(result3);
// Output:
// [
//   { shape: "square", color: "red", available: 3, ordered: 2 },
//   { shape: "circle", color: "blue", available: 0, ordered: 3 },
//   { shape: "square", color: "blue", available: 4, ordered: 4 }
// ]
登录后复制

类型安全示例

TypeScript 的类型系统可以帮助我们在编译时发现错误。例如,如果我们尝试传递一个无效的键,编译器会报错:

// @ts-expect-error
groupBySum(arr, ["blah"], ["ordered"]); // Error: Type '"blah"' is not assignable to type '"shape" | "ordered" | "color" | "available"'.ts(2322)
登录后复制

同样,返回对象的类型也是类型安全的。例如,在以下代码中:

const ans = groupBySum(arr, ["shape"], ["ordered"]);
登录后复制

ans 的类型是 Array<{ shape: string; ordered: number; }>。

注意事项

  • groupBySum 函数会丢弃任何未参与转换的键。这意味着,如果原始对象包含其他属性(例如 size),则这些属性将不会出现在结果对象中。
  • 用于求和的键必须是数值类型。
  • 此实现依赖于 Object.fromEntries,它在较旧的 JavaScript 环境中可能不可用。如果需要支持这些环境,可以使用 polyfill。

总结

groupBySum 函数提供了一种通用且类型安全的方法,可以根据任意数量的对象键对对象数组进行分组,并对另一组任意数量的键的值进行求和。 通过利用 TypeScript 的类型系统,该函数可以在编译时捕获错误,并确保代码的健壮性和可维护性。

以上就是使用 TypeScript 实现类型安全的 Group By 和 Sum 操作的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号