我想创建一个类,它具有从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);
如何根据循环中的对象键名创建类属性?
答案 0 :(得分:0)
为了允许类的动态属性,您需要定义索引签名,如下所示:
class MyClass {
[key: string]: any;
constructor(object) {
for (let key in object) {
this[key] = 'element';
}
}
}