How to Merge Objects in TypeScript

To merge objects in TypeScript, you can use the “spread syntax” or “Object.assign()” method.

Method 1: Merging Objects in TypeScript with Spread syntax(…)

The spread syntax(…) in Typescript can be “used to merge the elements of one or more objects into a new object”. The spread operator’s main objective is to spread an object’s elements.

Syntax

{ ...obj, key: "value" }

Example

const obj1 = { song1: "We are the world", song2: "Billie Jean" };
const obj2 = { album1: 'Thriller', album2: "Dangerous" };

const obj3 = { ...obj1, ...obj2 };

console.log(obj3);

Output

{
  song1: 'We are the world',
  song2: 'Billie Jean',
  album1: 'Thriller',
  album2: 'Dangerous'
}

In this example, the obj3 is a new object that contains all the properties from obj1 and obj2.

The object spread operator is a feature of ES6, so you will need to target ES6 or later when you compile your TypeScript. If you target an earlier version of ECMAScript, you can use Object.assign() instead, which has similar behavior.

Method 2: Merging Objects in TypeScript with Object.assign()

The Object.assign() method copies all enumerable (propertyIsEnumerable(prop) returns true) own properties from one or many source objects to a target object.

Syntax

Object.assign(target, ...sources);

Example

const obj1 = { song1: "We are the world", song2: "Billie Jean" };
const obj2 = { album1: 'Thriller', album2: "Dangerous" };

const obj3 = Object.assign({}, obj1, obj2);

console.log(obj3);

Output

{
  song1: 'We are the world',
  song2: 'Billie Jean',
  album1: 'Thriller',
  album2: 'Dangerous'
}

The target object’s properties are overwritten by other objects that have the same properties later in the parameter order.

That’s it.

Leave a Comment