Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

only allow value from certain object as type

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading