Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

Ecmascript function parameter with enum value

Is it possible to have an enum value of parameter in Ecmascript method?

For example for this case

export const testFunc = (param1) => {

};

For example, param can only take values of "val1","val2","val3"

export const testFunc = (param = {"val1","val2","val3"}) =>{

};

Upvotes: 0

Views: 312

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

As Snow says, JavaScript doesn't have enums. TypeScript does (details), so if you want enums (and various other features), you might consider using TypeScript, which compiles to JavaScript.

If you don't want to go that route, you can always define an enum-like object:

const TheEnum = {
    val1: 0,
    val2: 1,
    val3: 2,
    0: "val1",
    1: "val2",
    2: "val3",
    valid(value) {
        return typeof param === "number" && !!TheEnum[param];
    }
};

...and then validate the value you receive:

export const testFunc = (param) => {
    if (!TheEnum.valid(param)) {
        throw new Error("'param' must be a TheEnum value");
    }
    // ...
};

Note that that example "enum" has mappings both from symbolic names (val1, etc.0 to the values and from values to symbolic names. They do the in TypeScript, too; it's handy for when you want to show the name "val1" instead of the value 0 in messages, etc.

Upvotes: 2

Snow
Snow

Reputation: 4097

There no such thing as an enum in JS, but you could just check to see if the parameter is one of the allowed values:

export const testFunc = (param) =>{
  if (!["val1","val2","val3"].includes(param)) {
    throw new Error('Invalid param passed');
  }
  // rest of function
};

Upvotes: 3

Related Questions