0

I have two interfaces as below:

interface Interface1 {
  a: string;
  b: string;
  c: {
    d: string;
  };
}

interface Interface2 {
  aa: string;
  b: {
    cc: string;
  };
  d: string;
}

And an object:

const object1: DeepPartial<Interface1> = {
  a: 'a',
  c: {
    d: 'd',
  }
};

I'd like to create a new object object2 of type DeepPartial<Interface2> using some kind of mapping. I can do this using a bunch of if-statements but am wondering if there might be a cleaner way? For example, I could create a mapping like:

const mapping = [
  ['a', 'aa'],
  ['c.d', 'b.cc']
  ['b', 'd']
]

which would recursively look through the object and produce:

const object2: DeepPartial<Interface2> = {
  aa: 'a',
  b: {
    cc: 'd'
  }
}

Notice how object2 does not include d as b was not present in object1.

To summarise, I'd like to map a DeepPartial<Interface1> to a `DeepPartial recursively, so that properties that are ommited do not get mapped. I'm also open to any suggestions about how I could approach this problem differently.

For reference, the DeepPartial type is from here

Matt
  • 1,518
  • 4
  • 16
  • 30
  • So you want sorta `DeepMapped , string][]>` ? – Dimava Mar 29 '23 at 12:39
  • This is pretty complicated; forgetting the "partial" aspect of this and just mapping deeply from an input object to an output object, I have [this approach](https://tsplay.dev/wez0KN). Does that meet your needs or look close? I was concerned about what happens if you write a mapping like `["a", "b.c.d.e.f"]` where the input and output are different depths. If that happens then my version should work, but it's hard to keep the "optional" part in there. Anyway if this is close I can write up an answer; if not, what am I missing? – jcalz Mar 29 '23 at 13:47
  • This looks like a good start. The optional part is quite important, so if you could somehow figure it out then that would be great! – Matt Apr 11 '23 at 13:55
  • After two weeks of lying dormant this has completely fallen out of my head; if I do decide to take another look at this, what is the likely time frame for your response? – jcalz Apr 11 '23 at 14:00
  • Sorry, I can't guarantee anything. However, I greatly appreciate your time on this so far – Matt Apr 11 '23 at 14:15
  • Now that I've looked at it again, it's just not feasible to map optionality this way unless there's some guarantee that the mappings always obey the initial tree structure. If I have `{a?: {b: 0}, c: {d: 1}}` and the mapping is `[["a.b", "e.f"],["c.d", "e.g"]]`, there's no plausible way to decide whether the output `e` property should be optional or not. I'd rather just allow the output to be possibly `undefined` as done in my initial suggestion. But since I see that you can't place a reasonable boundary on the timeline, I think I'll just disengage entirely. Good luck! – jcalz Apr 11 '23 at 14:17

0 Answers0