TypeScript Object Assignment and Equality: References, Shallow and Deep Copy
Objects and arrays in JavaScript and TypeScript are reference values. Assigning one variable to another with = makes both variables refer to the same object:
A shallow copy duplicates only the first level. Nested objects remain shared. For a simple serializable object, one deep-copy option is:
| |
This does not preserve functions, dates, special types, or circular references. Modern environments can use structuredClone; Lodash also provides cloneDeep:
Two separate objects with identical properties are not equal under === because their references differ:
Class instances can also differ in their prototype chains. Decide whether your operation requires identity comparison, shallow copying, deep copying, or structural equality, and choose the corresponding mechanism explicitly.