You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript类型层面实现对象属性值求和?

实现SumUp<NS>类型的方案

直接上可运行的TypeScript代码,结合ts-arithmetic的Add类型,我们可以通过两步实现静态求和:

完整代码实现

import { Add } from 'ts-arithmetic';

// 辅助类型:把对象的所有值提取成元组
type Values<T> = T[keyof T][];

// 辅助类型:递归遍历元组并累加元素
type TupleSum<T extends number[], Acc extends number = 0> = 
  T extends [infer First extends number, ...infer Rest extends number[]]
    ? TupleSum<Rest, Add<Acc, First>>
    : Acc;

// 最终的SumUp类型
type SumUp<T> = TupleSum<Values<T>>;

// 测试用例
type NS = {
    readonly A: 4;
    readonly B: 4;
    readonly Op: 2;
    readonly Cin: 1;
};

type S = SumUp<NS>; // 类型为11,符合预期

代码说明

  • Values<T>:通过keyof T拿到对象的所有键,再用T[keyof T]获取对应值的联合类型,最后转成元组格式,方便递归处理。
  • TupleSum<T, Acc>:用递归逻辑遍历元组,每次取出第一个元素和累加器Acc做Add运算,再递归处理剩余元素;当元组为空时,返回累加器的最终结果。
  • SumUp<T>:组合两个辅助类型,先提取对象值的元组,再完成累加计算。

内容的提问来源于stack exchange,提问作者Jean-Philippe Pellet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 20:12:37