Julien Petitbon
Julien Petitbon

Reputation: 11

Typescript properties array of class

I'm trying to loop on each properties of class from a new object, without any property set. Object.keys() return an empty array. Maybe because none of properties are set. Do you know a way to loop on properties of a class or a fresh new object of this class ?

export class Perimeter {
  Id: string;
  Name: string;
  Description: string;
  Typapp: string;
}

 var tmp = new Perimeter();
 console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Result that I expect is ['Id', 'Name', 'Description', 'Typapp']

Thank you in advance

Upvotes: 0

Views: 487

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

The problem is you're not initializing those properties, so they only exist on the type, not at runtime. TypeScript will be warning you about that, saying that they've never been definitely assigned. For example:

Property 'Id' has no initializer and is not definitely assigned in the constructor. (2564)

Example

You need to initialize the properties for them to exist on the instance you're passing to Object.keys. You might do that in a couple of different ways. One of them is to use the public modifier on constructor parameters, which both creates a public property and automatically assigns the parameter's value to that property:

/*export*/ class Perimeter {
    constructor(
        public Id = "",
        public Name = "",
        public Description = "",
        public Typapp = ""
    ) {
    }
}

const tmp = new Perimeter();
console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Live Example

(I've included default values there because you've shown a call to the constructor that doesn't provide any arguments.)

But you can also write it explicitly:

/*export*/ class Perimeter {
    Id: string;
    Name: string;
    Description: string;
    Typapp: string;
    constructor(id = "", name = "", description = "", typapp = "") {
        this.Id = id;
        this.Name = name;
        this.Description = description;
        this.Typapp = typapp;
    }
}

const tmp = new Perimeter();
console.log('Object keys tmp', Object.keys(tmp)); //Object keys tmp []

Live Example

For a class that has both properties with fixed initial values and ones that are assigned in the constructor, I prefer to both declare them and then assign the ones that need it in the constructor, but for ones where all of the properties are constructor parameters, it makes for a handy shorthand. Either way, it's a matter of style.

Upvotes: 2

Related Questions