When working with TypeScript, I have defined an enum
, and now I want to create a function that accepts a parameter whose value is one of the enum's values. However, TypeScript does not validate the value against the enum, allowing values outside of the specified range to be passed. Is there a way to enforce this validation?
Example
enum myenum {
hello = 1,
world = 2,
}
const myfunc = (num:myenum):void => console.log(`num=${num}`);
myfunc(1); // num=1 (expected)
myfunc(myenum.hello); // num=1 (expected)
//THE ISSUE: I'm expecting next line to be a TS compile error, but it is not
myfunc(7); // num=7
Alternative
If I use a type
instead of an enum
, I can achieve a similar outcome in terms of validation. However, by using a type, I may lose some of the additional functionality provided by enums.
type mytype = 1|2;
const myfunc = (num:mytype):void => console.log(`num=${num}`);
myfunc(1);
myfunc(7); //TS Compile Error: Argument of type '7' is not assignable to a parameter of type 'mytype'