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

如何从对象嵌套属性生成指定的TypeScript联合类型?

从fieldMapping对象自动提取字段名联合类型

现有如下TypeScript对象:

export const fieldMapping = {
  'IP': { name: 'ipAddress', type: AirtableFieldType.STRING },
  'IP Country': { name: 'country', type: AirtableFieldType.STRING },
  'IP City': { name: 'city', type: AirtableFieldType.STRING },
  'IP Continent': { name: 'continent', type: AirtableFieldType.STRING },
  'Payment Processor': {
    name: 'paymentProcessor',
    type: AirtableFieldType.STRING,
  },
};

需要生成对应的联合类型:

type fieldNames = 'ipAddress' | 'country' | 'city' | 'continent' | 'paymentProcessor';

实现方法

利用TypeScript的typeof、keyof和索引类型特性,可自动提取所有name字段的字面量值组成联合类型,无需手动维护:

// 添加as const确保TypeScript保留字面量类型,避免被拓宽为string
export const fieldMapping = {
  'IP': { name: 'ipAddress', type: AirtableFieldType.STRING },
  'IP Country': { name: 'country', type: AirtableFieldType.STRING },
  'IP City': { name: 'city', type: AirtableFieldType.STRING },
  'IP Continent': { name: 'continent', type: AirtableFieldType.STRING },
  'Payment Processor': {
    name: 'paymentProcessor',
    type: AirtableFieldType.STRING,
  },
} as const;

// 自动生成目标联合类型
type FieldNames = typeof fieldMapping[keyof typeof fieldMapping]['name'];

原理说明

  1. typeof fieldMapping:获取fieldMapping的具体类型,包含每个键对应的结构信息
  2. keyof typeof fieldMapping:提取对象所有键的联合类型,即'IP' | 'IP Country' | 'IP City' | 'IP Continent' | 'Payment Processor'
  3. typeof fieldMapping[keyof typeof fieldMapping]:获取对象所有值的联合类型,也就是每个{name: 字面量字符串, type: ...}的结构联合
  4. 最后通过['name']索引,提取所有name字段的字面量值,组成目标联合类型

后续如果fieldMapping新增或修改字段,FieldNames类型会自动同步,无需手动调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:47:17