如何从对象嵌套属性生成指定的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'];
原理说明
typeof fieldMapping:获取fieldMapping的具体类型,包含每个键对应的结构信息keyof typeof fieldMapping:提取对象所有键的联合类型,即'IP' | 'IP Country' | 'IP City' | 'IP Continent' | 'Payment Processor'typeof fieldMapping[keyof typeof fieldMapping]:获取对象所有值的联合类型,也就是每个{name: 字面量字符串, type: ...}的结构联合- 最后通过
['name']索引,提取所有name字段的字面量值,组成目标联合类型
后续如果fieldMapping新增或修改字段,FieldNames类型会自动同步,无需手动调整。
内容的提问来源于stack exchange,提问作者Andronik Nazaryan
相关产品推荐
相关产品推荐

