猿问

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

说我有一堂课


Class A {}

并且想要遍历Class A属性(检查空值)只知道Class A将具有属性但可能在属性名称和属性数量上有所不同(例如)


Class A {

  A: string;

  B: string;

或者


Class A {

  B: string;

  C: string;

  D: string;

}

有没有办法遍历Class A属性并检查值是否为空?


温温酱
浏览 751回答 2
2回答

慕雪6442864

在运行时仅当您明确分配它们时。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 类在运行时不存在,因为它被转换为普通的旧 JavaScript。您可以获取对象实例的属性const a = { prop1: null, prop2: 'hello', prop3: 1 };const nullProps = obj => Object.getOwnPropertyNames(obj).filter(prop => obj[prop] === null);console.log(nullProps(a));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答