首页 > 解决方案 > TypeScript - 将一个对象的所有属性分配给另一个对象的简写方式

问题描述

我在 TypeScript 中有以下模式(但也只对 js 感兴趣)

const configs = {
  "hello": {
    x: 1,
    y: 1,
    z: 1
  }
}

class Foo {
  constructor(id) {
    this.id = id;
    const config = configs[id];
    this.x = config.x;
    this.y = config.y;
    this.z = config.z;
  }
}

const foo = new Foo("hello");
console.log(foo);

这有什么神奇的语法吗?我似乎记得有一种方法可以在 Python 中执行此操作(尽管我的谷歌搜索结果为空)

(编辑:为清楚起见,我想快速将 config 的所有属性分配为 Foo 的属性)

标签: javascriptpythontypescript

解决方案


你可以带上Object.assign想要的东西。

const configs = {
  "hello": {
    x: 1,
    y: 1,
    z: 1
  }
}

class Foo {
  constructor(id) {
    this.id = id;
    Object.assign(this, configs[id]);
  }
}

const foo = new Foo("hello");
console.log(foo);


推荐阅读