Typescript looping through class type properties

2019-03-24 02:09发布

How can one loop through the properties of a class in TypeScript? Take the following class for example:

export class Task implements Itask {
  public Id: number = 0;
  public Name: string;
  public Description: string;
  public Completed: boolean = false;
  public TaskType: TaskType;
}

Im want to retrieve the properties, hence: ["Id", Name", "Description", "Completed", "TaskType"]

Tried

GetTaskHeaders = () => {
  const _self = this;
  const tHead = $('<thead />').append('<tr />');

  for (let i = 0; typeof TodoApp.Task.arguments; i++) {
    const th = $('<th />');
    th.append(TodoApp.Task.arguments[i]);
    tHead.append(th);
  }

  console.log(tHead);

  return tHead;
};  

Unfortunately without success, i know using "TodoApp.Task.arguments" is incorrect. However, can someone show me the right way please?

2条回答
狗以群分
2楼-- · 2019-03-24 02:58

See How do I loop through or enumerate a JavaScript object?

In your case, something like:

for (var i in TodoApp.Task) {
    if (TodoApp.Task.hasOwnProperty(i)) {
        var th = $('<th />').append(TodoApp.Task[i]);
        tHead.append(th);
    }
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-03-24 03:01

Let's consider that all "not defined" properties i.e. all properties that are defined in the typescript class like (I wrote "not defined" and not undefined for a reason that will be clear below)

class A { 

   prop1: string
   prop2: number

} 

will not be enumerated by any of Object.keys or this.hasOwnProperty(k) since the autogen javascript has no knowledge of those properties. You have only one option, when you create your typescript class, that is to initialize all properties to default values like

class A { 

   prop1: string
   prop2: number
   prop3: B

   constructor() {
     this.prop1="";
     this.prop2=-1;
     this.prop3=null;
   }

} 

At this point you will get all the properties of A instance like in this mapping iteration from a dictionary

var a = new A();
for (var i in properties) {
   if (a.hasOwnProperty(i)) {
      a[i]=properties[i];
   }
}

If you don't like the default values solution, you can still do this using the magic undefined javascript keyword so that you do:

class A { 

   prop1: string = undefined
   prop2: number = undefined

} 

At this point the javascript counterpart will have all properties in the model and you will iterate them with Object.keys(this) or inspect them via the this.hasOwnProperty

查看更多
登录 后发表回答