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

TypeScript中如何为对象转换函数定义精准匹配的类型?

原有写法的问题

你之前的类型定义无法获得智能提示,核心问题是给wrap.custom使用了通用字符串索引签名{[key: string]: string}:这个写法只会告诉TS「custom是一个键为string、值为string的字典」,不会保留传入对象的具体键名信息,TS自然无法识别返回值里custom的具体属性。

支持严格键匹配+智能提示的实现

要实现返回值custom的键和入参wrap.custom的键完全一致,同时触发IntelliSense提示,需要用泛型捕获入参里custom对象的具体结构,不需要提前写死固定接口:

function transform<T extends Record<string, unknown>>(obj: {
  wrap: {
    custom: T
  }
}): { custom: T } {
  // 初始化时做类型断言,后续循环会完整拷贝所有属性,逻辑安全
  const returnedObj = { custom: {} as T };

  for (const key in obj.wrap.custom) {
    returnedObj.custom[key] = obj.wrap.custom[key];
  }

  return returnedObj;
}

// 测试示例
const a = { 
  wrap: { 
    custom: {
      test: 'test',
      count: 123,
      enabled: true
    }
  }
}
const b = transform(a);
// 此时输入b.custom. 编辑器会自动提示test、count、enabled三个属性,且属性类型和入参完全对应

关键说明

  • 泛型T会自动捕获你传入的obj.wrap.custom的完整类型(包括所有键名、对应值的类型),不会丢失具体结构信息
  • 返回值类型直接定义为{custom: T},从类型层面保证返回的custom结构和入参完全一致
  • 如果你需要强制约束custom里的所有值都为string类型,只需要把泛型约束从T extends Record<string, unknown>改成T extends Record<string, string>即可,TS会在传入不符合要求的入参时报错,同时依然保留智能提示能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:06:26