combine two objects in typescript

To combine two objects in TypeScript, you can use the Object.assign() method. This method merges the properties of two or more objects into a single target object. Here is an example:

index.ts
interface Person {
  firstName: string;
  lastName: string;
  age: number;
}

const person1: Person = { firstName: "John", lastName: "Doe", age: 30 };
const person2: Person = { firstName: "Jane", lastName: "Doe", age: 25 };

const personCombined = Object.assign({}, person1, person2);

console.log(personCombined);
// Output: { firstName: "Jane", lastName: "Doe", age: 25 }
374 chars
14 lines

In this example, we have two objects person1 and person2, defined with the interface Person. We then use Object.assign() to merge these two objects into a new object called personCombined. The first argument to Object.assign() is an empty object {}, which is necessary as it specifies the target object. The subsequent arguments are the objects to be merged into the target object, with the later objects overwriting the properties of the earlier objects.

In the console output, you can see that personCombined has the firstName, lastName, and age properties of person2, since it was the second argument in the Object.assign() method call.

gistlibby LogSnag