简体   繁体   中英

How can I get the numeric value of an enum variable in TypeScript?

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);

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM