Scrolling through enum, TypeScript, and jQuery

Hi, I am trying to develop a direct todo application using TypeScript and jQuery. I have an enumeration that lists the types of tasks:

export enum TaskType { FrontEnd, BackEnd, Designer }; 

However, going through emum using jquery.each or for a loop, I get the following result (values ​​then indices):

  FrontEnd, BackEnd, Designer, 0, 1, 2 

The following is a loop I am through the enumeration:

  constructor(e?: Object) { var template = this.FormTemplate; $(e).append(template); var sel = template.find('select'); /*$.each(TaskType, function (index, el) { sel.append("<option value='" + index + "'>" + el + "</option>"); });*/ for(var i=0; i < (typeof TaskType).length; i++){ sel.append("<option value='" + TaskType[i] + "'>" + TaskType[i] + "</option>"); } } 

Can someone tell me why this is?

+7
jquery enums enumeration ienumerable typescript
source share
1 answer

TypeScript enumerations when compiled in simple JS contain both a symbolic name and numeric values ​​as properties, and this explains why you get FrontEnd, BackEnd, Designer, 0, 1, 2 when trying to enumerate object properties. As far as I know, there is no compilation method to list only symbolic names. You can list all of them and skip all that is a number.

From this article, you can see exactly how the TypeScript enumerator compiles in JS.

If you have this TypeScript:

 //TypeScript declaration: enum StandardEnum {FirstItem, SecondItem, ThirdItem}; 

It compiles into this Javscript:

 //Compiled javascript: var StandardEnum; (function (StandardEnum) { StandardEnum[StandardEnum["FirstItem"] = 0] = "FirstItem"; StandardEnum[StandardEnum["SecondItem"] = 1] = "SecondItem"; StandardEnum[StandardEnum["ThirdItem"] = 2] = "ThirdItem"; })(StandardEnum || (StandardEnum = {})); ; 

This is essentially this result:

 var StandardEnum = { "FirstItem": 0, "SecondItem": 1, "ThirdItem": 2, "0": "FirstItem", "1": "SecondItem", "2": "ThirdItem" }; 

So, unless you specifically ignore numeric properties, there is no way to list only enumeration names.

You can do it like this:

  for (var item in StandardEnum) { if (StandardEnum.hasOwnProperty(item) && !/^\d+$/.test(item)) { console.log(item); } } 

Working demo: http://jsfiddle.net/jfriend00/65cfg88u/


FYI if you really want:

 var StandardEnum = { "FirstItem": 0, "SecondItem": 1, "ThirdItem": 2 }; 

Then maybe you shouldn't use an enumeration and just use this standard JS declaration. Then you can get the properties using Object.keys(StandardEnum) .

+18
source share

All Articles