Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
使用 TypeScript 实现类型安全的动态分组求和_创想鸟

使用 TypeScript 实现类型安全的动态分组求和

使用 typescript 实现类型安全的动态分组求和

本文详细介绍了如何使用 TypeScript 创建一个通用的、类型安全的 groupBySum 函数,该函数可以根据任意数量的对象键对对象数组进行分组,并对第二组任意数量的键的值进行求和。该函数避免了硬编码键名,并充分利用 TypeScript 的类型系统,保证了代码的健壮性和可维护性。

类型安全的 groupBySum 函数实现

以下是一个使用 TypeScript 实现的 groupBySum 函数,它满足了所有期望的要求:

/** * 对对象数组中的对象值进行求和,并按任意对象键进行分组。 * * @remarks * 此方法接受并返回一个对象数组。 * 生成的对象数组包含原始数组中对象键的子集。 * * @param arr - 要分组和求和的对象数组。 * @param groupByKeys - 用于分组的键的数组。 * @param sumKeys - 用于求和的键的数组。这些键必须引用数值。 * @returns 一个对象数组,按 groupByKeys 分组,并对 sumKeys 中的键的值进行求和。 */const groupBySum = (  arr: T[],  groupByKeys: K[],  sumKeys: S[]): Pick[] => {  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, key in curr ? curr[key] : 0]))          );        for (let key of sumKeys) {          groupedSum[key] = (groupedSum[key] || 0) + (curr[key] || 0);        }        return accu.set(key, groupedSum);      }, new Map())      .values(),  ];};

此函数接受三个参数:

arr: 要进行分组和求和的对象数组。groupByKeys: 用于分组的键的数组。sumKeys: 用于求和的键的数组。

该函数返回一个新的对象数组,其中包含按 groupByKeys 分组的原始数组中的对象,并且 sumKeys 中的值已被求和。

使用示例

以下是一些使用 JavaScript 等效代码的示例,基于以下 arr 数组:

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 },];const groupBySum = (arr, groupByKeys, sumKeys) => {  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(),  ];};console.log('groupBySum(arr, ["shape"], ["available"])')console.log(groupBySum(arr, ["shape"], ["available"]))console.log('nngroupBySum(arr, ["color"], ["ordered"])')console.log(groupBySum(arr, ["color"], ["ordered"]))console.log('nngroupBySum(arr, ["shape", "color"], ["available", "ordered"])')console.log(groupBySum(arr, ["shape", "color"], ["available", "ordered"]))

这些示例展示了如何使用 groupBySum 函数按不同的键进行分组,并对不同的值进行求和。

类型安全优势

TypeScript 实现是类型安全的。例如,如果我们尝试传递一个无效的键,编译器会报错:

groupBySum(arr, ["blah"], ["ordered"]);

错误信息如下:

Type '"blah"' is not assignable to type '"shape" | "ordered" | "color" | "available"'.ts(2322)

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

const ans = groupBySum(arr, ["shape"], ["ordered"])

是:

Array;

注意事项

任何未参与转换的键都会被删除。上面的示例不包含 color 或 available,因为它们不可能包含有意义的值。这是内置在返回类型中的,因此 TypeScript 知道不要期望它们。确保 sumKeys 中的键对应的值是数值类型,否则求和结果可能不正确。如果 groupByKeys 中存在重复的键,则会覆盖之前的分组结果。

总结

通过使用 TypeScript 的泛型和类型推断,我们可以创建一个通用的、类型安全的 groupBySum 函数,它可以根据任意数量的对象键对对象数组进行分组,并对第二组任意数量的键的值进行求和。这个函数不仅可以提高代码的可读性和可维护性,还可以避免运行时错误。

以上就是使用 TypeScript 实现类型安全的动态分组求和的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1515851.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
React MongoDB 项目中 ‘map’ 属性未定义的错误排查与解决
上一篇 2025年12月20日 09:38:14
使用 TypeScript 实现类型安全的通用分组求和函数
下一篇 2025年12月20日 09:38:24

相关推荐

发表回复

登录后才能评论
关注微信