0

Let's pretend that I have an interface A, that I am declaring as a class by following the Angular style guide. This class has many properties, and I want to fetch them names without having to assign any value to them. How can I achieve this ?

Class A:

export class A {
  property1: string;
  property2: string;
  ...
  property30: string;
}

I tried with instantiating a new object from this class and calling Object.keys and Object.getOwnPropertyNames but this two methods return an empty array because they are ignoring undefined value properties. Is there any way to bypass this behaviour ? Or am I breaking the JavaScript/TypeScript pattern ? :D

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
  • Possible duplicate of [Get properties of a class using Typescript](https://stackoverflow.com/questions/40636292/get-properties-of-a-class-using-typescript) – ochs.tobi Mar 08 '18 at 13:55
  • Nop it's not a duplicate because in the link provided they are giving some default values to the properties. – Mehdi Benmoha Mar 08 '18 at 14:16

2 Answers2

3

The way properties declarations work is that they are just a hint to the compiler that that property may exist at run-time. In JavaScript you don't need to declare fields, so until the field is assigned it will not exist on the object. If you initialize the field even just with null or undefined the field will appear on the object. This is the simplest way to achieve what you want.

The other way would be to use a decorator on every field. This would be more explicit but not shorter and not necessarily less error prone

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

Make sure your compiler supports class first. And then you have to do either interface or class. Ex. if it's a class, you need to do

class A {
    title = ''
}
var a = new A();
console.log(a);

declare title as a string, title: String = ''. Your writing is more for the interface. Here's the output,

Object {
    title: ""
}

Yeah, I understand your question better now, without assignment, it doesn't set the properties.

interface B {
    title: String;
}
class A implements B {
    title = '';
}
var a = new A();
console.log(a);

If that's the case, a simple solution is to give some default value of that property. Or going through a list to manually initialize all of them based by their type.

class A {
    keys = {
        title: 'String'
    }
}
windmaomao
  • 7,120
  • 2
  • 32
  • 36