EDIT: I stumbled upon this problem, because I made a wrong assumption. It is thus not a good question but the accepted answer explains my mistake well. I thus consider it still worth being archived here.
I have:
enum TimePeriod {
Custom = 0,
LastWeek = 1,
}
I also have a drop down HTML element with values 0 or 1, depending on what the user chose (Custom or LastWeek). I want a simple if (val === TimePeriod.Custom)
, but I cannot figure out what val
should be.
I understand that:
const val = $("#TimePeriod").val() as number;
will not work (ie. above if
always false), because val
is a number and not a TimePeriod
EDIT: This is the wrong assumption!
const val = $("#TimePeriod").val() as TimePeriod;
will not work, either, because the as TimePeriod
-part is lost then it is converted to JS. It is thus exactly the same as the first try.
Also tried:
const val = TimePeriod[$("#TimePeriod").val() as number];
But then val
is a string, e.g. "Custom"
What val
must actually be is an instance of a enum value, e.g. TimePerios.Custom
. But how do I obtain it dynamically having only number 0
?
I read Cast int to enum strings in Typescript and even How do I convert a string to enum in TypeScript? but it does not help.