How can I get the numeric value of an enum variable in TypeScript?
typescript
Solution
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 });
Problem
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); ```