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.ts374 chars14 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