TypeScript Shallow Copy and Deep Copy

Copy concepts in TypeScript

Copying

In programming, copying is broadly divided into two approaches.

  1. Deep Copy
  2. Shallow Copy

Deep Copy

  • Deep copy is a copying method where the original value is not affected even if the copied value changes.
  • In TypeScript, primitive types such as number and boolean basically behave as deep copies.
let original = 1;
let copied = original;
copied += 2;

console.log(original, copied); // 1 3

The original original does not change, and only copied changes.

Shallow Copy

  • Shallow copy is a copying method where the copy and the original share the same reference.
  • In TypeScript, objects and arrays basically behave as shallow copies.
const originalArray = [5, 3, 9, 7];
const shallowCopiedArray = originalArray;

shallowCopiedArray[0] = 0;

console.log(originalArray, shallowCopiedArray); 
// [0, 3, 9, 7] [0, 3, 9, 7]

Because the array originalArray shares the same reference as shallowCopiedArray, modifying one also affects the other.

Copying with the spread operator (…)

  • The spread operator (...) can be used like a deep copy for one-dimensional arrays only.
const oArray = [1, 2, 3, 4];
const deepCopiedArray = [...oArray];

deepCopiedArray[0] = 0;

console.log(oArray, deepCopiedArray); 
// [1, 2, 3, 4] [0, 2, 3, 4]

The original array stays the same, and only the copy changes.

Note: If you need to completely copy arrays containing nested objects or nested objects themselves, the spread operator alone does not perform a deep copy.
In that case, use something like JSON.parse(JSON.stringify(obj)).


Summary

Type/Method Copy type Characteristics
number, boolean Deep copy Original and copy are independent
Object, Array Shallow copy Original and copy share a reference
Spread operator ... One-dimensional deep copy Preserves the original for one-dimensional arrays/objects