简体   繁体   English

如何在TypeScript中获取枚举变量的数值?

[英]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. 我需要将枚举变量的数值上传到REST服务。

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) $http是AngularJS的HTTP服务)

Both methods will lead to $http serializing the enum variable as a JSON object: 这两种方法都会导致$http将枚举变量序列化为JSON对象:

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): 以下工作,但它被标记为错误,因为TypeScript中不存在成员.Value (它存在于Javascript中):

var enumVar: MyEnum = ...;
var enumValue: number = enumVar.Value;
$http.put(url, enumValue);

You're probably using older version of TypeScript. 可能正在使用旧版本的TypeScript。 In version >= 0.9, enums are string/number based by default, which means it should serialize the way you want it. 在版本> = 0.9中,枚举是默认情况下基于字符串/数字,这意味着它应该按照您希望的方式序列化。

TS TS

enum MyEnum {
    hello, bye
}

var blah:MyEnum = MyEnum.bye;

alert({myEnumVal: blah}); // object {myEnumVal:1}

generated JS: 生成JS:

var MyEnum;
(function (MyEnum) {
    MyEnum[MyEnum["hello"] = 0] = "hello";
    MyEnum[MyEnum["bye"] = 1] = "bye";
})(MyEnum || (MyEnum = {}));

var blah = 1 /* bye */;

alert({ val: blah });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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