Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript spread deep copy with arrays

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?

like image 726
AJM Avatar asked Oct 27 '17 07:10

AJM


1 Answers

new object2 with a deep copy of all object1 items

No. Spread is always a shallow copy.

Example

let orig = { arr: [1,2,3] }
let copy = {...orig}
copy.arr.push(4)
console.log(orig.arr) // 1 2 3 4

More

Some docs: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#object-spread-and-rest

like image 101
basarat Avatar answered Sep 19 '22 19:09

basarat