我正在 TypeScript 中定义一个类。 因此,使用展开运算符,我可以发出这样的命令:
class Foo {
constructor(data: IDataStructure){
const { ...k } = data; // and then k has taken over all the properties of data. Great!
}
public render () {
return(<div/>
);
}
}
现在,我想做同样的事情,但不是将属性放在 k
中,而是放在正在创建的当前对象中。 IE。我想做一些类似 const { ...this } = data;
在 Typescript 中执行此操作的聪明方法吗?
最佳答案
您不能使用 spread 向现有对象添加属性。当前没有语法可以做到这一点;相反,使用 Object.assign
:
Object.assign(this, data);
示例(在 JavaScript 中):
class Example {
constructor(data) {
Object.assign(this, data);
}
}
const e = new Example({answer: 42});
console.log(e.answer); // 42
请注意,Object.assign
对属性进行浅复制。因此,如果 data
的属性之一引用了一个对象,则该引用将被复制,并且 data
和 this
将引用同一个对象:
const data = {
answer: 67,
obj: {
prop: "value"
}
};
Object.assign(this, data);
console.log(this.obj === data.obj); // true, it's a shallow copy, they both refer
// to the same object
如果您需要深层复制,其中复制data
也会生成data.obj
的副本,请参阅this question's answers .
关于node.js - 如何将扩展运算符与 'this' 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772641/