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

TypeScript中为CountersData接口赋值属性的更高效方法?

问题描述

当前给CountersData接口属性赋值的实现逻辑如下:

  • 调用flattenObject工具方法,从responseDeploymentData中提取最深层级的键值数据,得到扁平化对象
  • 逐行手动将扁平化对象中对应字段赋值给CountersData类型的实例

这种逐行赋值的写法冗余度较高,需要更高效简洁的实现方式。

原有代码实现

interface CountersData {
  //more properties

  count_targets?: number;
  count_targets_excluded?: number;
  count_targets_pending?: number;
  count_targets_in_progress?: number;
  count_targets_completed?: number;
  count_targets_failed?: number;
}
// 后续业务代码
  const countersData = {} as CountersData;
  let targetData: any = flattenObject(responseDeploymentData);
  countersData.count_targets = targetData.count_targets;
  countersData.count_targets_excluded = targetData.count_targets_excluded;
  countersData.count_targets_pending = targetData.count_targets_pending;
  countersData.count_targets_in_progress = targetData.count_targets_in_progress;
  countersData.count_targets_completed = targetData.count_targets_completed;
  countersData.count_targets_failed = targetData.count_targets_failed;

已尝试的方案

['count_targets', 'count_targets_excluded'].forEach(key => countersData[key] = targetData[key]);

解决方案

你尝试的forEach遍历赋值思路是可行的,核心优化方向是补全类型约束+抽离通用逻辑,避免重复代码同时保证类型安全,下面是两种常用的实现方式,按需选择即可:

方案1:通用字段提取方法(推荐)

抽一个可复用的pick工具方法,后续其他需要从大对象里挑同名字段的场景都能直接用,TS会自动做类型校验,要是不小心拼错字段名,编译阶段就会报错,不用等到运行时踩坑:

/**
 * 从源对象中提取指定键对应的字段,返回目标结构对象
 */
function pick<T, K extends keyof T>(source: Partial<T>, keys: K[]): Pick<T, K> {
  return keys.reduce((result, key) => {
    result[key] = source[key];
    return result;
  }, {} as Pick<T, K>);
}

// 业务代码使用
const targetData = flattenObject(responseDeploymentData);
// 定义需要提取的字段列表,类型约束为CountersData的键名集合
const counterFieldKeys: (keyof CountersData)[] = [
  'count_targets',
  'count_targets_excluded',
  'count_targets_pending',
  'count_targets_in_progress',
  'count_targets_completed',
  'count_targets_failed'
];
const countersData: CountersData = pick(targetData, counterFieldKeys);

后续如果CountersData接口新增同名字段,只要在counterFieldKeys数组里新增对应字段名即可,不需要重复写赋值语句。

方案2:直接解构赋值(适合字段少、无复用需求的场景)

如果不需要复用逻辑,也可以直接在对象初始化时解构赋值,比逐行赋值更紧凑,也能通过TS类型校验:

const targetData = flattenObject(responseDeploymentData);
const countersData: CountersData = {
  count_targets: targetData.count_targets,
  count_targets_excluded: targetData.count_targets_excluded,
  count_targets_pending: targetData.count_targets_pending,
  count_targets_in_progress: targetData.count_targets_in_progress,
  count_targets_completed: targetData.count_targets_completed,
  count_targets_failed: targetData.count_targets_failed
};

注意事项

别直接用扩展运算符{...targetData}给countersData赋值,flattenObject拍平对象后会带出很多嵌套层级的字段,大部分和CountersData没关系,直接展开会把多余属性混进目标对象,容易引发后续逻辑bug。


内容的提问来源于stack exchange,提问作者user19251203

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 20:31:07