如何在TypeScript中从接口生成枚举以规避Parse Server魔法字符串?
从TypeScript接口自动生成Parse类属性键,避免魔法字符串
你已经通过定义ItemAttributes接口实现了Parse类的类型约束,但不想手动维护ItemKeys枚举来规避魔法字符串。下面提供几种无需手动编写枚举的方案,实现类型安全的属性访问:
方案1:用常量对象+keyof类型替代枚举
直接创建一个与接口字段一一对应的常量对象,结合keyof类型确保类型一致性:
import { Attributes, Object } from 'parse' export interface ItemAttributes extends Attributes { color: string size: number enabled: boolean } export class Item extends Object<ItemAttributes> { constructor (data?: Partial<ItemAttributes>) { super('Item', data as ItemAttributes) } } // 与接口字段同步的常量对象 export const ItemKeys = { color: 'color', size: 'size', enabled: 'enabled' } as const; // 导出类型,方便其他场景使用 export type ItemKeys = keyof ItemAttributes;
使用方式和枚举完全一致:
const myItem = new Item(); const color = myItem.get(ItemKeys.color); // 类型安全,自动推导为string
这种方式简单直观,虽然需要手动维护对象,但只要和接口字段保持同步,就能保证类型安全,适合中小项目。
方案2:用Proxy自动生成属性键
利用TypeScript的keyof类型约束和JS的Proxy特性,完全无需手动维护字段映射:
import { Attributes, Object } from 'parse' // 通用工具函数:根据接口生成属性键访问器 function createModelKeys<T extends Record<string, any>>() { return new Proxy({}, { get(_, prop: string) { return prop; } }) as { [K in keyof T]: K }; } export interface ItemAttributes extends Attributes { color: string size: number enabled: boolean } export class Item extends Object<ItemAttributes> { constructor (data?: Partial<ItemAttributes>) { super('Item', data as ItemAttributes) } } // 生成Item的属性键 export const ItemKeys = createModelKeys<ItemAttributes>();
使用时,ItemKeys.color会自动返回字符串'color',同时TypeScript会检查你只能访问ItemAttributes中存在的属性:
const myItem = new Item({ size: 10 }); const size = myItem.get(ItemKeys.size); // 类型为number,类型安全 // 以下代码会触发类型错误:属性'nonexistent'不存在于类型'{ color: "color"; size: "size"; enabled: "enabled"; }' // myItem.get(ItemKeys.nonexistent);
这种方式彻底解放手动维护的工作量,只要接口更新,ItemKeys自动同步,适合大多数项目场景。
方案3:编译时自动生成枚举(大型项目可选)
如果确实需要标准的枚举类型,可以通过TypeScript自定义Transformer或脚本工具,在编译阶段从接口自动生成枚举代码。不过这种方式需要额外配置构建流程,复杂度较高,适合字段极多的大型项目。
内容的提问来源于stack exchange,提问作者epietrowicz
相关产品推荐
相关产品推荐

