Michael Hilus
Michael Hilus

Reputation: 1828

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?

Upvotes: 5

Views: 3663

Answers (2)

Kokodoko
Kokodoko

Reputation: 28128

In OOP terms you don't define your properties after creating instances, you define them in your class

In your example both Marc and Peter have an age so you don't need to merge anything. You could use the contructor to pass a specific value for that instance:

let marc = new Person("marc", 20)
let peter = new Person("peter", 30)

class Person {
    constructor(private name:string, private age:number){
       console.log("I am " + this.name + " my age is " + this.age)
    }
}

If there is a property that no person except Marc has, then you can let Marc extend Person.

class Person {

}

class Marc extends Person {
    car:string
}

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222474

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.

Upvotes: 4

Related Questions