简体   繁体   English

使用Typescript反射获取类属性和值

[英]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将具有属性,但属性名称和属性数量可能有所不同的情况下,才想遍历Class A属性(检查空值)

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? 有没有一种方法可以遍历Class A属性并检查值是否为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. TypeScript类在运行时不存在,因为它已被转换为普通的旧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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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