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 };