Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve property names for all properties in a class in typescript excluding methods

Tags:

typescript

I am trying to make my code as reactive as possible and need render my view based on the properties of a class, How do I retrieve the property names only form a class excluding methods etc.

for example.

export class Customer { 
    customerNumber: string; 
    name: string; 
    salesContact: string; 
    salesContactEmailAddress: string; 
    salesContactNumber: string; 
    execContact: string; 
    constructor(data?: any) {
        ...
    }

    toJSON() {
        ...
    }

    clone() {
        ...
    }
}

I need it to give me something the returned to be an Array of strings like this

fields: string[] = ["customerNumber", "name", "salesContact", "salesContactEmailAddress", "salesContactNumber", "execContact"];

1 Answers

JavaScript cannot hold the type information for a class in any way, so the short answer is that it's not possible in most cases.

Like Thomas Devries mentioned, you cannot perform real reflection in TypeScript.

The longer answer is that it's possible in instances of a class, and as long as the properties have been initialized. Then you just use Object.keys().

This won't work:

class A {
  prop: string; 

  constructor() {
  }

  fn() {
    // ..
  }
}
const a = new A();
console.log(Object.keys(a)); // []

But this will:

class A {
  prop: string = "hello"; 

  constructor() {
    // Or here:
    // this.prop = "hello";
  }

  fn() {
    // ..
  }
}
const a = new A();
console.log(Object.keys(a)); // ["prop"]

In some instances, you might want to use Object.getOwnPropertyNames too. There's some important distinctions between that and Object.keys().

You can find even more information on enumerability here.

like image 118
zeh Avatar answered Oct 18 '25 07:10

zeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!