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

TypeScript:如何将键数组转换为对象联合类型?

解决方案:用TypeScript映射类型生成对象联合类型

1. 基于对象接口直接生成

你可以利用映射类型结合索引访问类型,自动生成目标联合类型,完全替代手动编写的分支:

interface IObject {
  id: string;
  name: string;
  age: number;
}

// 简化后的类型定义
type SET_PROPERTY_PAYLOAD = {
  [K in keyof IObject]: {
    id: string;
    propertyName: K;
    value: IObject[K];
  };
}[keyof IObject];

2. 基于字符串数组生成

如果你的需求是从字符串数组(而非对象接口)出发,只需把keyof IObject替换为数组推导的联合类型即可:

// 定义常量字符串数组
const objKeys = ["id", "name", "age"] as const;
// 从数组生成字符串字面量联合类型
type ObjKeys = typeof objKeys[number];

interface IObject {
  id: string;
  name: string;
  age: number;
}

// 基于数组生成对象联合类型
type SET_PROPERTY_PAYLOAD = {
  [K in ObjKeys]: {
    id: string;
    propertyName: K;
    value: IObject[K];
  };
}[ObjKeys];

原理说明

  1. 映射类型:{ [K in KeyType]: ... }会遍历KeyType中的每个键,为每个键生成对应的对象结构;
  2. 索引访问:[keyof IObject](或[ObjKeys])会把映射类型的所有值提取出来,自动合并为联合类型;
  3. 类型窄化:生成的联合类型中,propertyName的字面量类型会和value的类型自动绑定,TypeScript会根据propertyName的值自动推断value的类型。

效果验证

使用这个类型时,TypeScript会自动做类型检查:

function updateProperty(payload: SET_PROPERTY_PAYLOAD) {
  // 当payload.propertyName为"age"时,payload.value自动推断为number类型
}

// 合法调用
updateProperty({ id: "user-1", propertyName: "age", value: 30 });
// 类型错误:value应为number,传入了字符串
updateProperty({ id: "user-1", propertyName: "age", value: "30" });

内容的提问来源于stack exchange,提问作者C.Tale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:48:34