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

如何实现TypeScript对象键值反转函数并保留类型映射关系

实现精准类型推断的键值对反转函数mapSelf

要解决TypeScript中反转对象键值对后类型推断不精准的问题,我们可以利用**键重映射(Key Remapping)**特性定义函数返回类型,确保反转后的每个属性值都对应原对象的具体键类型,而非联合类型。

实现代码

// 约束原对象的值必须是合法的对象键类型(string/number/symbol)
function mapSelf<T extends Record<string, string | number | symbol>>(obj: T): { [K in keyof T as T[K]]: K } {
  const result = {} as { [K in keyof T as T[K]]: K };
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const value = obj[key];
      // 类型断言确保赋值时类型匹配
      result[value as keyof typeof result] = key as K;
    }
  }
  return result;
}

测试示例

const original = { a: "aee", b: "bee", c: "cee" };
const reversed = mapSelf(original);

// 此时 reversed.aee 的类型会被精准推断为 "a",而非 "a"|"b"|"c"
console.log(reversed.aee); // 输出 "a"
console.log(reversed.bee); // 输出 "b",类型推断为 "b"

关键说明

  1. 泛型约束:T extends Record<string, string | number | symbol>确保原对象的属性值可以作为新对象的键(JavaScript对象的键仅支持string、number或symbol类型)。
  2. 键重映射:{ [K in keyof T as T[K]]: K }是核心逻辑——遍历原对象的每个键K,将原属性值T[K]作为新对象的键,原键K作为新对象的属性值,以此建立一一对应的类型关系。
  3. 重复值处理:若原对象存在重复属性值,TypeScript会自动将对应新键的类型推断为联合类型(比如原对象{a: "aee", d: "aee"},反转后reversed.aee的类型为"a"|"d"),这与实际运行时的覆盖逻辑一致。

内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:42:44