使用 TypeScript 实现类型安全的通用分组求和函数

使用 TypeScript 实现类型安全的通用分组求和函数

本文介绍如何使用 typescript 创建一个通用的、类型安全的 groupBySum 函数。该函数可以根据对象数组中的任意数量的键进行分组,并对第二组任意数量的键的值进行求和。通过使用 TypeScript 的类型系统,可以确保代码的类型安全,并在编译时捕获潜在的错误。

实现 groupBySum 函数

以下 TypeScript 函数满足所有所需标准:

/**  * 对对象数组中的对象值进行求和,按任意对象键分组。  *  * @remarks  * 此方法接受并返回一个对象数组。  * 生成的对象数组包含原始数组中对象键的子集。  *  * @param arr - 要分组和求和的对象数组。  * @param groupByKeys - 用于分组的键的数组。  * @param sumKeys - 用于求和的键的数组。这些键必须引用  *    数值。  * @returns 一个对象数组,按 groupByKeys 分组,并对 sumKeys 中的键的值求和。  */ 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(),   ]; };

这个函数使用了 TypeScript 的泛型和类型推断,以确保类型安全。

  • T 是输入对象数组中对象的类型。
  • K 是 T 类型的键,用于分组。
  • S 是 T 类型的键,用于求和。

Pick 类型用于创建一个新的类型,该类型仅包含 T 类型中 K 和 S 键。这确保了返回的对象只包含分组键和求和键。

使用示例

以下 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(arr, ["shape"], ["available"]) [   { shape: 'square', available: 7 },   { shape: 'circle', available: 0 } ]   groupBySum(arr, ["color"], ["ordered"]) [   { color: 'red', ordered: 2 },   { color: 'blue', ordered: 7 } ]   groupBySum(arr, ["shape", "color"], ["available", "ordered"]) [   { 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 实现是类型安全的。例如,如果我们尝试传递一个无效的键…

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<{ shape: string; ordered: number }>;

注意事项

请注意,任何未参与转换的键都会被删除。上面的示例不包含 color 或 available,它们不可能包含有意义的值。这是内置在返回类型中的,因此 TypeScript 知道不要期望它们。

总结

使用 TypeScript 创建 groupBySum 函数可以提供类型安全和通用性。通过利用 TypeScript 的类型系统,可以在编译时捕获潜在的错误,并确保代码的正确性。这个函数可以应用于各种场景,例如数据分析、报表生成等。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享