typescript 只允许来自特定对象的值作为类型

slmsl1lt  于 2023-06-30  发布在  TypeScript
关注(0)|答案(2)|浏览(171)

我想使用MyBar作为枚举替换。所以在我的函数testme中,我希望参数value只能是1|2。我如何才能做到这一点?

const MyBar = {
  Benchpress : 1,
  Squats : 2
};

testMe(MyBar.Squats); // Error Argument number is not  assignable to parameter `Benchpress| Squats`

// I would like to use it like this:
testMe(MyBar.Squats);
testMe(2);
// And this should be an error 
testMe(3);

function testMe(value:  keyof typeof  MyBar)
{
  console.log(value);
}
kpbwa7wx

kpbwa7wx1#

将自定义ValueOf类型与as const组合使用

const MyBar = {
  Benchpress : 1,
  Squats : 2
} as const;

type ValueOf = typeof MyBar[keyof typeof MyBar];

testMe(MyBar.Squats); // works
testMe(2); // works
testMe(3); // doesn't work

function testMe(value: ValueOf) {
  console.log(value);
}
bz4sfanl

bz4sfanl2#

type MyBarValue = typeof MyBar[keyof typeof MyBar];

相关问题