如何将TypeScript枚举子集作为接口键使用?编译报错求解
解决TypeScript枚举子集作为接口键的编译报错问题
报错原因
你遇到的错误是因为TypeScript不允许在类型字面量的计算属性名中使用值层面的联合表达式(比如Operator.gt | Operator.gte),它要求计算属性名必须是字面量类型或unique symbol类型。
可行解决方案
方案1:使用Record工具类型结合枚举类型子集
先定义需要的操作符类型子集,再用Record工具类型生成对应的键值对结构:
enum Operator { eq = 'eq', neq = 'neq', lt = 'lt', lte = 'lte', gt = 'gt', gte = 'gte', in = 'in' } // 从枚举中提取需要的操作符类型子集 type RangeOperators = Operator.gt | Operator.gte | Operator.lt | Operator.lte; interface Filter { range: Record<RangeOperators, string>; }
方案2:单独列出每个枚举值作为计算属性名
直接将每个需要的枚举值单独作为键,避免使用联合表达式:
enum Operator { eq = 'eq', neq = 'neq', lt = 'lt', lte = 'lte', gt = 'gt', gte = 'gte', in = 'in' } interface Filter { range: { [Operator.gt]: string; [Operator.gte]: string; [Operator.lt]: string; [Operator.lte]: string; } }
方案3:用常量对象替代枚举(可选)
如果不需要枚举的运行时特性,可以用as const定义常量对象,更灵活地提取类型:
const Operator = { eq: 'eq', neq: 'neq', lt: 'lt', lte: 'lte', gt: 'gt', gte: 'gte', in: 'in' } as const; type OperatorType = typeof Operator[keyof typeof Operator]; type RangeOperators = typeof Operator.gt | typeof Operator.gte | typeof Operator.lt | typeof Operator.lte; interface Filter { range: Record<RangeOperators, string>; }
内容的提问来源于stack exchange,提问作者revy
相关产品推荐
相关产品推荐

