Ben Aston
Ben Aston

Reputation: 55739

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

In C# I might use an enumeration.

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

Upvotes: 9

Views: 412

Answers (3)

Jamie Dixon
Jamie Dixon

Reputation: 53989

Basically, you can't.

Strong typing doesn't exist in JavaScript, so it's not possible to confine your input parameters to a specific type or set of values.

Upvotes: 0

dougajmcdonald
dougajmcdonald

Reputation: 20047

We sometimes define a variable in a JS class 'Enumerations' along these lines:

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

And then reference it just like a C# enumeration.

Upvotes: 7

Sirko
Sirko

Reputation: 74076

There is no enumeration type in JavaScript. You could, however, wrap an object with a getter and setter method around it like

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; }
   };
 })();

Upvotes: 1

Related Questions