I want to use MyBar as an enum replacement. So in my function testme I want that the parameter value can only be 1|2. How can I achieve this?
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);
}
>Solution :
Use the custom ValueOf Type with a combination of 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);
}