Skip to content

clone

Creates a shallow copy of a value — one level deep, unlike cloneDeep.

Unlike a plain { ...value } spread, this correctly reconstructs Date, Map, Set, and arrays instead of producing an empty (or wrong-shaped) plain object for them. Primitives are returned as-is. Any other object (including class instances not listed above) has its own enumerable string keys shallow-copied into a plain object — the same fallback cloneDeep uses, so the two stay consistent for types neither one special-cases.

Available since v3.0.0

import { clone } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { clone } from 'helpers4/object';
clone<T>(value: T): T
ParameterTypeDescription
valueTThe value to shallow-clone

T — A shallow copy of value

Top-level keys are copied; nested values still share references (shallow).

const obj = { a: 1, b: { c: 2 } };
const copy = clone(obj);
copy.b === obj.b // => true (same nested reference)

Correctly clones Date/Map/Set, unlike a spread

Section titled “Correctly clones Date/Map/Set, unlike a spread”

{ …new Date() } produces {} — clone() doesn’t have that problem.

clone(new Map([['a', 1]]))
// => new Map with the same entries, not {}

View source on GitHub