-1

I have an interface (interfaceA) that has 2 properties and another one (interfaceB) that has 3 properties (The numbers are just for example).

I have created an object (type: interfaceB) and I would like to create another object (type: interfaceA) and copy only the values from the common properties from B to A.

  • One solution is to copy all the fields and delete the third one, but I don't like that.

  • Another solution is to create a new Object with only the properties that I need but I don't like that either.

In both solutions, if someone adds a property to one of the interfaces, I would have to add or delete the property in the assignment also.

Is there any solution to my problem?

I have created a StackBlitz to help you understand better.

StPaulis
  • 2,844
  • 1
  • 14
  • 24

1 Answers1

1

Does this solve your problem?

function copyValues(objA: interfaceA, objB: interfaceB) {
  Object.entries(objB).forEach(([key, value]) => {
    if (objA.hasOwnProperty(key)) {
      objA[key] = value;
    }
  });
}

PS: If not, then it is not possible, you need to have the information of which keys objectA has at runtime - AFAIK there is no way to generate that from the types. You can get a type that represents what you want e.g. Extract<keyof interfaceB, keyof interfaceA> but there is no way to get that into a runtime-usable form.

StPaulis
  • 2,844
  • 1
  • 14
  • 24
Mike Jerred
  • 9,551
  • 5
  • 22
  • 42
  • Nope, because `hasOwnProperty` doesn't work if the `objectA` has not instantiated with the right properties in the first place. – StPaulis Sep 10 '20 at 12:44
  • 1
    What you want is not possible then, you need to have the information of which keys `objectA` has at runtime - AFAIK there is no way to generate that from the types. You can get a type that represents what you want e.g. `Extract` but there is no way to get that into a runtime-usable form. – Mike Jerred Sep 10 '20 at 13:27