javascripttypescriptcopyinstance

How to merge class instances in TypeScript?


I have a class like this:

class Person {
    private _age: number;

    get age(): number {
        return this._age;
    }

    set age(value: number) {
        this._age = value;
    }
}

And an instance of that class:

let peter = new Person();
peter.age = 30;

I want to have another instance of that class by simply using the spread operator:

let marc = {
    ...peter,
    age: 20
}

But this does not result in an instance of Person but in an object without the getter and setter of Person.

Is it possible to merge class instances somehow or do I need to use new Person() again for mark?


Solution

  • Spread syntax is supposed to produce plain object, so it isn't applicable. If new class instance is needed, it should be created with new. If an object has to be merged with other properties, Object.assign can be used:

    let marc = Object.assign(
        new Person()
        peter,
        { age: 20 }
    );
    

    Since Object.assign processes own enumerable properties, the result may be undesirable or unexpected, depending on class internals; it will copy private _age but not public age from peter.

    In any special case a class should implement utility methods like clone that is aware of class internals and creates an instance properly.