Typescript looping through class type properties

前端 未结 2 1203
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 11:16

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

export class T         


        
相关标签:
2条回答
  • 2021-01-01 12:02

    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

    0 讨论(0)
  • 2021-01-01 12:05

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题