Coming from a background in statically typed languages, the main benefit I get from enums is compile time error catching.
I'm writing a little program in Javascript, and I find myself wanting something like an enum, perhaps like this:
var Fruit = {
BANANA: "BANANA",
APPLE: "APPLE",
PEAR: "PEAR";
};
But I see no advantage to this. I might as well just use strings everywhere this 'enum' is required.
Should I just be using strings in javascript in place of enum types in other languages?
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
If your set of parameters is limited and known at compile time, use enum . If your set of parameters is open and unkown at compile time, use strings. Save this answer.
The they are useless at runtime argument and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.
In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.
It is good way to extract common things like magic numbers/strings or similar. Imagine that you have BANANA
all over the place then for some reason you need to change BANANA
to SOMETHING_ELSE
, without approach you are using in question you need to make a change in every single place.
var foo = {
bar: "baz"
}
So using foo.bar
instead of hardcoded string "baz"
all over the place, can save your time and possible bugs when it comes to changing "baz"
to something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With