According to Snow on this thread, JavaScript lacks enums. However, TypeScript does support enums (more information here), so if you require enums (along with other features), TypeScript could be a viable option as it compiles to JavaScript.
If TypeScript isn't the path you want to take, an alternative approach is to create 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 verify the received value:
export const testFunc = (param) => {
if (!TheEnum.valid(param)) {
throw new Error("'param' must be a TheEnum value");
}
// ...
};
It's worth noting that this example "enum" provides mappings for both symbolic names (val1
, etc.) and their corresponding values, similar to how it's done in TypeScript. This can be useful when you need to display the name "val1"
instead of its associated value 0
in messages or other contexts.