JavaScript idiom for restricting a string to a number of discrete values

In C #, I can use an enumeration.

In JavaScript, how can I limit a value to a set of discrete values โ€‹โ€‹idiomatically?

+7
source share
3 answers

Sometimes we define a variable in the Enumerations class of the JS class:

var Sex = { Male: 1, Female: 2 }; 

And then reference it the same way as listing in C #.

+7
source

Basically, you cannot.

Strong typing does not exist in JavaScript, so it is not possible to restrict input parameters to a specific type or set of values.

0
source

There is no enumeration type in JavaScript. However, you could wrap the object using the get and setter method, for example

 var value = (function() { var val; return { 'setVal': function( v ) { if ( v in [ listOfEnums ] ) { val = v; } else { throw 'value is not in enumeration'; } }, 'getVal': function() { return val; } }; })(); 
0
source

All Articles