CodyBugstein CodyBugstein - 3 months ago 9
TypeScript Question

Is there a way to get to all variables of a certain type in a class?

Say I have a Typescript class like

class MyClass {
myNum1:number;
myNum2:number;
myNum3:number;
myString:string;
myBoolean:boolean;
}


Is there any way for to get all of the instance variables of type
number
?

Answer

Your code "compiles" to this:

var MyClass = (function () {
    function MyClass() {
    }
    return MyClass;
}());

with nothing in there as you can see... however if you initialize your properties it will result some like this:

source TS:

class MyClass {
    myNum1: number = 0;
    myNum2: number = 0;
    myNum3: number = 0;
    myString: string = "";
    myBoolean: boolean = false;
}

result JS:

var MyClass = (function () {
    function MyClass() {
        this.myNum1 = 0;
        this.myNum2 = 0;
        this.myNum3 = 0;
        this.myString = "";
        this.myBoolean = false;
    }
    return MyClass;
}());

then you can check instance properties:

var instance = new MyClass();
Object.keys(instance) //["myNum1", "myNum2", "myNum3", "myString", "myBoolean"]
instance["myNum1"] // 0

with that in mind you can filter the properties that you need:

var numerics = Object.keys(instance).map(k => instance[k]).filter(v => v.constructor.name === "Number")
console.log(numerics) //[0, 0, 0]