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

如何限制对象属性值为枚举中已存在的有效值?

问题原因

在TypeScript中,数字枚举的类型默认会被视为number的子类型,这意味着任何数字都能通过类型校验,哪怕它不在枚举定义的成员里。这就是为什么值3能被赋值给Item['value']的原因。

解决方案

方案1:使用字面量联合类型替代枚举

如果不需要枚举的运行时特性(比如反向映射),直接定义字面量联合类型是最简单的方式:

type AcceptableValues = 0 | 1 | 2 | 4;

interface Item {
  value: AcceptableValues;
}

const x: Item = { value: 3 }; // 类型错误:Type '3' is not assignable to type 'AcceptableValues'

方案2:保留枚举同时限制类型为字面量联合

如果需要保留枚举的运行时对象(比如需要通过枚举键获取值),可以提取枚举成员的字面量值组成联合类型:

enum AcceptableValues {
  a = 0,
  b = 1,
  c = 2,
  d = 4,
}

// 提取枚举所有成员值的字面量联合类型
type AcceptableValueLiteral = typeof AcceptableValues[keyof typeof AcceptableValues];

interface Item {
  value: AcceptableValueLiteral;
}

const x: Item = { value: 3 }; // 类型错误:Type '3' is not assignable to type 'AcceptableValueLiteral'

方案3:使用const断言的对象替代枚举

这种方式既保留了类似枚举的键值对结构,又能直接得到字面量联合类型,且编译后不会生成额外的枚举代码:

const AcceptableValues = {
  a: 0,
  b: 1,
  c: 2,
  d: 4,
} as const;

type AcceptableValues = typeof AcceptableValues[keyof typeof AcceptableValues];

interface Item {
  value: AcceptableValues;
}

const x: Item = { value: 3 }; // 类型错误:Type '3' is not assignable to type 'AcceptableValues'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:05:21