I am faced with the challenge of working with two interfaces:
public interface ObjectOne {
field1: string;
field2: string;
field3: string;
field4: string;
field5: string;
...
}
public interface ObjectTwo {
field2: string;
field5: string;
field8: string;
...
}
Let's say that ObjectOne
has 20 fields and ObjectTwo
has 10 fields (all of which are part of ObjectOne
).
At the end of an action, I need to copy the fields from ObjectOne
to ObjectTwo
, but without manually mapping each field like so:
objTwo.field2 = objOne.field2;
objTwo.field5 = objOne.field5;
objTwo.field8 = objOne.field8;
...
I am aware that I can destructure ObjectOne
as follows:
const {field2, field5, field8, fieldX, ...} = objOne;
and then assign these fields to objTwo
in one go:
objTwo = {field5, field8, fieldX, ...};
However, I was hoping for a more elegant solution, almost like an inverse of a spread operator. Speaking of which, here is an example of using the spread operator:
const objOne = {...objTwo, field1, field3, field4, field6, ...};
Using the spread operator on objTwo would result in it inheriting all the fields from objOne, regardless of their object type declarations.