Jonathan002 Jonathan002 - 3 years ago 150
TypeScript Question

How can I create class properties from a for loop going through object keys?

I want to create a class that has it's properties generated from a for loop going over object keys as shown below:

e.g. I want to create:

// Result I'm hoping for..
class MyClass {
public earth = 'element'
public fire = 'element'
public wind = 'element'
}

// What I'm trying to do..
let object = {
earth: 'stone',
fire: 'flame',
wind: 'air'
}

class MyClass {
constructor(object) {
for (let key in object) {
console.log(key);
this.${key} = 'element';
}
}
}

let dynamicPropClass = new MyClass(object);


How can I create class properties based on a object key names in a loop?

Answer Source

In order to allow dynamic properties on a class you need to define an index signature like this:

class MyClass {
   [key: string]: any;

   constructor(object) {
       for (let key in object) {          
         this[key] = 'element';
       }
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download