
本文介绍如何使用 TypeScript 创建一个通用的、类型安全的 groupBySum 函数。该函数可以根据对象数组中的任意数量的键进行分组,并对第二组任意数量的键的值进行求和。通过使用 TypeScript 的类型系统,可以确保代码的类型安全,并在编译时捕获潜在的错误。
以下 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 的泛型和类型推断,以确保类型安全。
Pick
以下 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('\n\ngroupBySum(arr, ["color"], ["ordered"])')
console.log(groupBySum(arr, ["color"], ["ordered"]))
console.log('\n\ngroupBySum(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 实现是类型安全的。例如,如果我们尝试传递一个无效的键...
专为中小型企业定制的网络办公软件,富有竞争力的十大特性: 1、独创 web服务器、数据库和应用程序全部自动傻瓜安装,建立企业信息中枢 只需3分钟。 2、客户机无需安装专用软件,使用浏览器即可实现全球办公。 3、集成Internet邮件管理组件,提供web方式的远程邮件服务。 4、集成语音会议组件,节省长途话费开支。 5、集成手机短信组件,重要信息可直接发送到员工手机。 6、集成网络硬
0
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 的类型系统,可以在编译时捕获潜在的错误,并确保代码的正确性。这个函数可以应用于各种场景,例如数据分析、报表生成等。
以上就是使用 TypeScript 实现类型安全的通用分组求和函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号