如何用MyBar替代枚举,限制testMe函数参数仅为1或2?
问题描述
希望将MyBar用作枚举的替代方案,要求testMe函数的value参数仅能取1或2这两个值。允许传入MyBar.Squats、2这类合法值,传入3则触发错误。但当前定义的testMe函数参数类型为keyof typeof MyBar,导致传入MyBar.Squats时报错,请问该如何实现需求?
const MyBar = { Benchpress : 1, Squats : 2 }; testMe(MyBar.Squats); // Error Argument number is not assignable to parameter `Benchpress| Squats` // 我希望能这样调用: testMe(MyBar.Squats); testMe(2); // 而这样应该报错 testMe(3); function testMe(value: keyof typeof MyBar) { console.log(value); }
解决方案
问题核心是你把参数类型定义成了对象的键类型(Benchpress|Squats),但实际需要的是对象值的类型(1|2)。按以下步骤调整即可实现需求:
1. 保留对象值的字面量类型
默认情况下TypeScript会把MyBar里的数值推断为宽泛的number类型,而非具体的1和2。添加as const断言,让类型系统精确保留字面量信息:
const MyBar = { Benchpress: 1, Squats: 2 } as const; // 断言为只读常量,锁定值的字面量类型
2. 定义参数为对象值的联合类型
将testMe的参数类型改为typeof MyBar[keyof typeof MyBar],这个表达式会自动提取MyBar所有属性值的联合类型(即1|2):
function testMe(value: typeof MyBar[keyof typeof MyBar]) { console.log(value); }
测试验证
testMe(MyBar.Squats)→ 正常执行(值为2,符合类型要求)testMe(2)→ 正常执行testMe(3)→ 触发类型错误(3不在1|2的联合类型范围内)
额外优化:给值类型起别名
如果需要多次使用这个值类型,可以定义一个类型别名提升代码可读性:
type MyBarValue = typeof MyBar[keyof typeof MyBar]; function testMe(value: MyBarValue) { console.log(value); }
内容的提问来源于stack exchange,提问作者heaxyh
相关产品推荐
相关产品推荐

