跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

使用 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 = ( 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, 0])) ); for (let key of sumKeys) { groupedSum[key] += curr[key]; } return accu.set(key, groupedSum); }, new Map()) .values(), ]; };
代码解释: 泛型定义: groupBySum 函数使用了三个泛型类型:T 代表输入数组中对象的类型,K 代表用于分组的键的类型,S 代表用于求和的键的类型。K 和 S 都被约束为 keyof T,这意味着它们必须是 T 类型对象中存在的键。 参数: arr: 要进行分组和求和的对象数组。 groupByKeys: 一个 字符串数组 ,包含用于分组的键。 sumKeys: 一个字符串数组,包含用于求和的键。 reduce 方法: 使用 reduce 方法遍历输入数组 arr。reduce 方法的第一个参数是一个累加器函数,它接收两个参数: accu: 累加器,这里是一个 Map 对象,用于存储分组后的结果。键是根据 groupByKeys 生成的字符串,值是分组后的对象。 curr: 当前正在处理的数组元素。 生成分组键: 使用 groupByKeys.map((key) => curr[key]) 从当前对象 curr 中提取用于分组的键的值,并将它们连接成一个字符串作为分组键。 创建或更新分组对象: accu.get(key) || ...: 尝试从累加器 accu 中获取与当前分组键对应的对象。如果不存在,则创建一个新的对象。 Object.assign(...): 如果分组键不存在,则使用 Object.assign 创建一个新的对象,该对象包含: 从 groupByKeys 中提取的 键值对 。 从 sumKeys 中提取的键,其初始值为 0。 累加求和: 遍历 sumKeys 数组,将当前对象 curr 中对应键的值累加到分组对象中。 TypeScript-45分钟入门课件源码 TypeScript-45分钟入门课件源码 下载 返回结果: 将累加器 accu 中的所有值提取到一个新的数组中,并返回该数组。 类型安全: 函数的返回类型 Pick[] 确保返回的数组中的对象只包含用于分组的键 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 的类型系统,该函数可以在编译时捕获错误,并确保代码的健壮性和可维护性。

相关文章