I have a common typescript class with some functions.
When I do this.selected = Object.assign({} as AssignedTestType, newTestType);
the selected instance does not own that functions which are in the type AssignedTestType
.
How can I make a 'deep' copy with object.assign? or any alternative method?
Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.
assign() , and Object. create() ) do not create deep copies (instead, they create shallow copies). As can be seen from the code above, because a deep copy shares no references with its source object, any changes made to the deep copy do not affect the source object.
The first argument in Object. assign is called the “target” and will MUTATE.
object.assign does not copy functions
That's untrue
let x = {a: y => y * 2}
let z = Object.assign({}, x)
console.log(z.a(5)); // 10
the selected instance does not own that functions which are in the type AssignedTestType.
Now this part is true. Object.assign
will only do a shallow copy and will only enumerate own props
If the properties you're looking to copy are in the prototype of newTestType
, they will not be copied, since Object.assign
only copies an object instance's own properties.
The alternatives are to either instantiate whatever constructor you used to create newTestType
, and assign the resulting instance to this.selected
, or to create an empty object and set its prototype to newTestType
. In either case, Object.assign
is the wrong tool to use here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With