assign()
assign<
Target,Source>(object, ...sources):Target&Source
Assigns own enumerable string keyed properties of source objects to the destination object.
DEPRECATED
Use Object.assign() or spread syntax directly instead.
Type Parametersโ
Target: Target extends Record<string, unknown>โ
The type of the destination object.
Source: Source extends Record<string, unknown>โ
The type of the source objects.
Parametersโ
object: Targetโ
The destination object.
sources: ...Source[]โ
The source objects.
Returns: Target & Sourceโ
The destination object.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
assign (Lodash, Radashi) ยท merge (es-toolkit, Remeda, Modern Dash) ยท mergeRight (Ramda) ยท โ (Effect, Antfu)
Exampleโ
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { c: 5, d: 6 };
// โ Deprecated approach
const result = assign(target, source1, source2);
console.log(result); // { a: 1, b: 3, c: 5, d: 6 }
// โ
Recommended approach (mutable)
const resultNative = Object.assign(target, source1, source2);
console.log(resultNative); // { a: 1, b: 3, c: 5, d: 6 }
// โ
Recommended approach (immutable)
const resultImmutable = { ...target, ...source1, ...source2 };
console.log(resultImmutable); // { a: 1, b: 3, c: 5, d: 6 }
How it works?โ
Assigns source properties to destination object.
Deprecated: Use Object.assign() or spread operator directly (ES2015).
Native Equivalentโ
// โ assign(target, source)
// โ
Object.assign(target, source)
// โ
{ ...target, ...source }
Use Casesโ
Merge objects ๐โ
Combine objects into one.
Object.assign({}, defaults, options);
// or
{ ...defaults, ...options };
Shallow copyโ
Create shallow object copy.
const copy = { ...original };
// or
const copy = Object.assign({}, original);
Apply defaultsโ
Merge defaults with provided options.
const config = { ...defaultConfig, ...userConfig };