1

I am defining a class in TypeScript. So with the spread operator I can issue something like this:

class Foo {
  constructor(data: IDataStructure){
      const { ...k } = data; // and then k has taken over all the properties of data. Great!
  }

  public render () {

    return(<div/>

   );
  }
}

Now, I would love to do the same but not to put the properties in k but in the current object that is being created. I.e. I would like to do something like const { ...this } = data; Is there any smart way to do this in Typescript?

Jose
  • 1,389
  • 3
  • 16
  • 25

1 Answers1

4

You can't use spread to add properties to an existing object. There's no current syntax way of doing it; instead, use Object.assign:

Object.assign(this, data);

Example (in JavaScript):

class Example {
    constructor(data) {
        Object.assign(this, data);
    }
}
const e = new Example({answer: 42});
console.log(e.answer); // 42

Note that Object.assign does a shallow copy of the properties. So if one of data's properties refers to an object, that reference is copied over, and both data and this will refer to the same object:

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

If you need a deep copy, where copying data also makes a copy of data.obj, see this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I just found out it is not really working. What it does actually is to screw up your class. From that point on, whenever you wanna access the variables of the class thourough 'this' it is screwed as 'this' is now pointing to data. – Jose Aug 18 '18 at 08:10
  • @Jose - No, it isn't. `this` has a shallow copy of what's on `data`. I've added a note about deep cloning to the answer, but nothing in your question suggested that you wanted a deep copy. – T.J. Crowder Aug 18 '18 at 08:17