TypeScript

Deep Clone with structuredClone

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Forget JSON.parse(JSON.stringify(...)) — modern runtimes (Node 17+, all current browsers) ship structuredClone, which handles Dates, Maps, Sets, typed arrays, and cycles correctly.
TypeScript
Raw
export function deepClone<T>(value: T): T {
  if (typeof structuredClone === 'function') {
    return structuredClone(value);
  }
  // Older-runtime fallback (loses Dates/Maps/Sets fidelity)
  return JSON.parse(JSON.stringify(value)) as T;
}

const original = {
  date:    new Date(),
  map:     new Map([['a', 1]]),
  nested:  { items: [1, 2, 3] },
};
const copy = deepClone(original);
copy.nested.items.push(4);
console.log(original.nested.items);   // [1, 2, 3] — untouched
console.log(copy.date instanceof Date); // true — Date preserved
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.