使用 Typescript 反射获取类属性和值 [英] Get Class properties and values using Typescript reflection
本文介绍了使用 Typescript 反射获取类属性和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有课
Class A {}
并且想要遍历 Class A
属性(检查空值),只知道 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 (e.g.)
Class A {
A: string;
B: string;
}
或
Class A {
B: string;
C: string;
D: string;
}
有没有办法遍历 Class A
属性并检查值是否为空?
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 反射获取类属性和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文