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"];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With