简体   繁体   中英

Get Class properties and values using Typescript reflection

Say I have a class

Class A {}

And would like to iterate through Class A properties (checking for null values) only knowing that Class A will have properties but might vary in property names and number of properties (eg)

Class A {
  A: string;
  B: string;
} 

or

Class A {
  B: string;
  C: string;
  D: string;
}

Is there a way I can iterate through Class A properties and check if the values are null?

At Runtime

Only if you explicitly assign them.

class A {
  B: string | null = null;
  C: string | null = null;
  D: string | null = null;
}
const a = new A();
for (let key in a) {
  if (a[key] == null) {
    console.log('key is null:', key);
  }
}

TypeScript class do not exist at run time as it is transpiled down to plain old JavaScript. You can get the properties of an instance of an Object

 const a = { prop1: null, prop2: 'hello', prop3: 1 }; const nullProps = obj => Object.getOwnPropertyNames(obj).filter(prop => obj[prop] === null); console.log(nullProps(a)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM