ReactHustle

How to Merge Objects in Typescript

Jasser Mark Arioste

Jasser Mark Arioste

How to Merge Objects in Typescript

Hello! In this tutorial, you'll learn how to merge objects in Typescript. Merging objects in Javascript and Typescript is an everyday operation, especially in React where the state is immutable. Immutability is one of the best practices to avoid hard-to-find bugs where the state is updated in multiple places of a web application. In these cases, you'll have to create another object to update the state of an object.

Currently, there are two ways to merge objects in typescript:

  1. Using Object.assign()
  2. Using the spread syntax(...)

Merge Objects Using Object.assign() #

The Object.assign() static method copies all the enumerable & own properties from one source object to a target object. The first parameter is the target, and the following parameters are the sources. The Object.assign() method can also accept multiple sources. Below is an example of how to use it.

const merged = Object.assign(target, ...sources);
1

Actual usage:

const user = { name: "John Doe", age: 24 }
const address = { street: "225 Baker St.", city: "London" }

const merged = Object.assign({}, user, address);
console.log(merged) // { name: "John Doe", age: 24, street: "225 Baker St.", city: "London" }
12345

As a best practice, it's best to use an empty object ({}) for the target parameter so that you don't mutate the source objects.

The resulting type of the merged object is inferred. Meaning, you cannot add or remove fields to the merged object unless you explicitly specify the type:

// ❌ Error: Property 'likes' does not exist on type '{ street: string; city: string; name: string; age: number; }'.
merged.likes = 10 

// -------
type Merged = {
  name: string;
  age: number;
  street: string;
  city: string;
  likes?: number
}
// Explicitly specify the merged type
const merged: Merged = Object.assign({}, user, address);

merged.likes = 10; // No Error
123456789101112131415

Merge Objects Using the Spread Syntax #

You can also use the spread syntax(...). It is commonly used to copy all properties of an object to another, it's also commonly used in ReactJS to update the state of an object without mutating the previous object. Using the same example:

const user = { name: "John Doe", age: 24 }
const address = { street: "225 Baker St.", city: "London" }

const merged = {
  ...user,
  ...address
} 
console.log(merged) // { name: "John Doe", age: 24, street: "225 Baker St.", city: "London" }
12345678

Similar to Object.assign(), once the objects have been merged, the resulting type is inferred. So you cannot add or remove fields because it throws a compile-time error unless you explicitly specify a type.

// ❌ Error: Property 'likes' does not exist on type '{ street: string; city: string; name: string; age: number; }'.
merged.likes = 10 

/// ----
type Merged = {
  name: string;
  age: number ;
  street: string;
  city: string;
  likes?: number;
};
const user = { name: "John Doe", age: 24 };
const address = { street: "225 Baker St.", city: "London" };

const merged: Merged = {
  ...user,
  ...address,
};

merged.likes = 10; // No error
1234567891011121314151617181920

However, you can still modify the fields of the merged object.

merged.name = "Jane Doe" // No error

console.log(merged) // { name: "Jane Doe", age: 24, street: "225 Baker St.", city: "London" }
123

Performance #

In terms of performance, Using Object.assign() is 2x faster based on the test on benchmark test using the same data.

MethodPerformance
Object.assign()3,027,817 ops/sec
Spread Syntax6,300,552 ops/sec

However, this is only one test and it's really hard to tell if this is really the case. If you want to test the performance of both operations. You'll have to try it using your own data. What happens if the source objects have more properties?

Conclusion #

You learned how to merge objects in typescript using Object.assign() and the spread syntax.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Learn more about Object.assign and spread syntax.

Credits: Image by Đức Tình Ngô from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle