I am confused by the spread operator in typescript
When I use .the spread operator to make a copy of object1.
var object2 = { ...object1, };
I get a new object2 with a deep copy of all object1 items even if object1 contains other objects.
However if object1 has an array in it a shallow copy is performed. In that case it seems to maintain the relationship between the array values in object1 and object2.
Is there a way to deep copy arrays using the spread operator?
new object2 with a deep copy of all object1 items
No. Spread is always a shallow copy.
let orig = { arr: [1,2,3] }
let copy = {...orig}
copy.arr.push(4)
console.log(orig.arr) // 1 2 3 4
Some docs: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#object-spread-and-rest
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