如何通过对象键从for循环创建类属性?

时间:2017-09-30 10:31:50

标签: typescript

我想创建一个类,它具有从for循环遍历对象键生成的属性,如下所示:

e.g。我想创建:

// 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);   

如何根据循环中的对象键名创建类属性?

1 个答案:

答案 0 :(得分:0)

为了允许类的动态属性,您需要定义索引签名,如下所示:

class MyClass {
   [key: string]: any;

   constructor(object) {
       for (let key in object) {          
         this[key] = 'element';
       }
   }
}