I need to upload the numeric value of an enum variable to a REST service.
How can I get the numeric value of the enum variable?
I tried the following two methods:
var enumVar: MyEnum = ...;
$http.put(url, { enumVar: enumVar });
This won't work also:
var enumVar: MyEnum = ...;
$http.put(url, { enumVar: <number>enumVar });
($http
is AngularJS's HTTP service)
Both methods will lead to $http
serializing the enum variable as a JSON object:
enumVar: {
Name: 'MyEnumMemberName',
Value: 2,
}
instead of just uploading the numeric value:
enumVar: 2,
The following works, but it is marked as an error, since the member .Value
does not exist in TypeScript (it exists in Javascript):
var enumVar: MyEnum = ...;
var enumValue: number = enumVar.Value;
$http.put(url, enumValue);
Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statements like int variables.
Numeric Enum. Numeric enums are number-based enums i.e. they store string values as numbers. Enums can be defined using the keyword enum. Let's say we want to store a set of print media types. The corresponding enum in TypeScript would be:
These identifiers have constant values. In typeScript enums can be created by using enum keyword. By default enums are assign numeric values starting with 0; As seen above an enum is compiled to an object with each element assigned to a numeric value starting with zero.
As seen above an enum is compiled to an object with each element assigned to a numeric value starting with zero. At the same time each enum is given string values by their numeric keys (Reverse mappings). That means we can access their numeric values or their string values:
Heterogeneous enums are enums that contain both string and numeric values. Enum in TypeScript supports reverse mapping. It means we can access the value of a member and also a member name from its value. Consider the following example.
You're probably using older version of TypeScript. In version >= 0.9, enums are string/number based by default, which means it should serialize the way you want it.
TS
enum MyEnum {
hello, bye
}
var blah:MyEnum = MyEnum.bye;
alert({myEnumVal: blah}); // object {myEnumVal:1}
generated JS:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["hello"] = 0] = "hello";
MyEnum[MyEnum["bye"] = 1] = "bye";
})(MyEnum || (MyEnum = {}));
var blah = 1 /* bye */;
alert({ val: blah });
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