说我有像
这样的Typescript类class MyClass {
myNum1:number;
myNum2:number;
myNum3:number;
myString:string;
myBoolean:boolean;
}
有没有办法获得number
类型的所有实例变量?
答案 0 :(得分:4)
您的代码“编译”到此:
var MyClass = (function () {
function MyClass() {
}
return MyClass;
}());
在那里没有任何东西,你可以看到...但是如果你初始化你的属性,它会产生这样的结果:
来源TS:
class MyClass {
myNum1: number = 0;
myNum2: number = 0;
myNum3: number = 0;
myString: string = "";
myBoolean: boolean = false;
}
结果JS:
var MyClass = (function () {
function MyClass() {
this.myNum1 = 0;
this.myNum2 = 0;
this.myNum3 = 0;
this.myString = "";
this.myBoolean = false;
}
return MyClass;
}());
然后你可以检查实例属性:
var instance = new MyClass();
Object.keys(instance) //["myNum1", "myNum2", "myNum3", "myString", "myBoolean"]
instance["myNum1"] // 0
考虑到这一点,您可以过滤所需的属性:
var numerics = Object.keys(instance).map(k => instance[k]).filter(v => v.constructor === Number)
console.log(numerics) //[0, 0, 0]