How to iterate through all properties and its values in Typescript class

Dharshni picture Dharshni · Mar 17, 2017 · Viewed 7.2k times · Source

How do I iterate through list of class properties and get the values of each (only the properties and not the functions)

Please help.

Answer

Nitzan Tomer picture Nitzan Tomer · Mar 17, 2017

You can't do that, if you look at the compiled code of:

class Person {
    name: string;
    age: number;
    address: Address;
}

You'll see that those properties aren't part of it:

var Person = (function () {
    function Person() {
    }
    return Person;
}());

Only if you assign a value then the property is added:

class Person {
    name: string = "name";
}

Compiles to:

var Person = (function () {
    function Person() {
        this.name = "name";
    }
    return Person;
}());

You can use a property decorator for that.