You need to enable JavaScript to run this app. TypeScript中如何基于接口公共匹配键从源对象克隆目标对象
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何基于接口公共匹配键从源对象克隆目标对象

TypeScript 公共键类型匹配克隆工具实现

实现核心逻辑

通过双层校验满足筛选规则,兼顾类型安全与运行时正确性:

  • 编译期层面:基于TS结构类型系统,筛出同时满足「源与目标的公共键」「源属性类型可赋值给目标对应属性类型」的键集合,自动推导返回值类型,避免类型不匹配
  • 运行时层面:遍历源对象的自有键,逐一对不符合规则的键值做过滤,抵消TS运行时类型擦除的影响,保证实际输出结果符合预期

代码实现

编译期工具类型

// 提取源与目标类型中,满足匹配规则的键集合
type MatchingKeys<Source, Target> = {
  [K in keyof Source & keyof Target]: Source[K] extends Target[K] ? K : never
}[keyof Source & keyof Target]

// 定义最终返回值的类型:从源类型中提取所有匹配的键
type MatchedResult<Source, Target> = Pick<Source, MatchingKeys<Source, Target>>

通用运行时函数

function cloneMatchedProps<Source, Target>(
  source: Source,
  // 传入目标类型的形状占位对象:运行时从该对象读取目标键集合、各键的期望类型,用于做校验
  targetShape: Target
): MatchedResult<Source, Target> {
  const result = {} as MatchedResult<Source, Target>
  for (const key of Object.keys(source) as (keyof Source)[]) {
    // 跳过不属于目标结构的非公共键
    if (!(key in targetShape)) continue
    const sourceValue = source[key]
    const expectType = typeof targetShape[key as keyof Target]
    // 校验源值的实际类型与目标期望类型是否一致
    if (typeof sourceValue !== expectType) continue
    // 匹配通过的键值写入结果
    Object.assign(result, { [key]: sourceValue })
  }
  return result
}

题目场景验证

  1. 修正原类型定义的语法问题(原定义缺少类型赋值的等号):
type A = {
  one: string,
  two: number,
  three: string | undefined
}

const a: A = { one: 'test', two: 1, three: 'test'};

type B = {
  one: string,
  three: number,
  four: number
}
  1. 准备目标类型B的运行时占位对象(仅需保证键名、值类型和B一致,值内容可随意填占位):
const bSample: B = { one: '', three: 0, four: 0 }
  1. 调用工具函数获取结果:
const matched = cloneMatchedProps(a, bSample)
// 实际运行输出:{ one: 'test' }
// TS自动推导的返回值类型:{ one: string }

逐键筛选结果

完全符合需求的过滤规则:

  • one:是A与B的公共键,源值为string、目标要求string,类型匹配,保留
  • two:仅存在于A中,非公共键,过滤
  • three:虽为公共键,但源值是string、目标要求number,类型不匹配,过滤
  • four:仅存在于B中,源对象无对应取值,过滤

扩展说明

  • 目前运行时类型判断基于typeof,覆盖所有JS基础类型场景,若需支持对象、数组、自定义类的类型校验,可在类型判断分支接入自定义类型守卫扩展能力
  • 编译期类型推导基于TS原生结构类型规则,可自动识别可选属性的类型差异,比如源的可选属性是string | undefined的类型,目标要求非空string时会被自动排除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 20:24:02