0

Let me start with an example:

let john = {
    name: "John",
    age: 21
}

let newAge = {
    age: 22
}


john = {...john , ...newAge};

By doing the above I can update john by passing the newAge object with the dot notation (spread operator). The advantage here is that it is easy to extend this behavior and easily update the values of an object by passing the updated values in partial object.

I want to do something similar with a class.

interface IPerson {
    name?: string;
    age?: number;   

class Person implements IPerson {
    update(value: IPerson) {
        // somehow make it work?
    }
}

I just don't see how I can do this with this.

Is this possible?

Lucas
  • 668
  • 1
  • 5
  • 17
  • No. The purpose of `... ` is to build new objects not mutate existing ones. `Object.assign` is a utility that will be useful in your case but you won't be able to leverage the `... ` sugar. Also, classes are overused and misused. – Aluan Haddad Feb 17 '21 at 14:07
  • Care to explain why? I'm using the classes to have local instances of persistent (database) objects and easier data manipulation. – Lucas Feb 17 '21 at 14:31
  • It depends on the frameworks you're using of course, but plain plastic old objects are simpler, more flexible, and easier to work with. – Aluan Haddad Feb 17 '21 at 15:33
  • Which is not always good. Flexible things might break easier if you're not careful. It really depends on the use case. It's like saying javascript is better than typescript because if allows you to work more freely and without as many constraints. – Lucas Feb 17 '21 at 16:05
  • I don't think you understand what I mean by flexibility but I don't have time to clarify. Classes don't provide any guarantees they just are harder to work with syntactically – Aluan Haddad Feb 17 '21 at 16:11

0 Answers0