Spread only overlapping elements of an object into a new one with TypeScript

Viewed 127

When you spread an object in TypeScript into another object all elements are spread. Also the elements which are not in the target type (new object after spread).

type ObjectA = {
    a: string;
    b: string;
}

type ObjectB = ObjectA & {
    c: string;
}

const instanceObjectB: ObjectB = {
    a: 'A',
    b: 'B',
    c: 'C'
}

const spreadObjectA: ObjectA = {...instanceObjectB};
console.log(spreadObjectA);

This is expected behavior for me, but I also see some problems with it. The spreadObjectA contains more data as it should and if I serialize and send it over to an API also the unnecessary data is included. So I usually "handcraft" the new objects:

const overlapObjectA: ObjectA = {a: instanceObjectB.a, b: instanceObjectB.b};
console.log(overlapObjectA);

I tried to do some research, but it was difficult to find anything. So my questions are:

  1. Is there a flag in the TypeScript compiler or an option in ESLint, which helps me to prevent me from living in danger?
  2. Can I configure Babel, so only the overlapping elements are spread? So the spread becomes type aware?
  3. How you would deal with this in a big project with many developers?

Here the code in the TypeScript Playground.

Updated question

  1. What would be an easy way to remove the excess properties?
0 Answers
Related