Skip to content Skip to sidebar Skip to footer

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 prop

Solution 1:

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);
  }
}

Solution 2:

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));

Post a Comment for "Get Class Properties And Values Using Typescript Reflection"