6

I have a nested object that I want to flatten whilst also concatenating the nested keys. I want to go from this:

const nested = {
  a: {
    b: {
      c: {
        d1: "hello",
        d2: 42,
      },
    },
  },
};

To this:

const flattened = {
  "a.b.c.d1": "hello",
  "a.b.c.d2": 42,
};

If I have a function that performs this transform, e.g.

function flatten<TNested>(nested: TNested): Flattened<TNested> {...}

Is it possible to define the type Flattened that does the right thing and correctly infers the type of flattened?

I appreciate it might just not be possible with current TypeScript, but would like to know for sure!

andre_b
  • 427
  • 5
  • 12
  • It actually is possible, and I believe this question is a duplicate of this: https://stackoverflow.com/questions/58434389/typescript-deep-keyof-of-a-nested-object – Alex Wayne Nov 04 '21 at 17:42
  • 1
    If I copy the code from that question (and make one minor change to put a dot in the paths) I get [this solution](https://tsplay.dev/WK7a8W). Does that work for you? – jcalz Nov 04 '21 at 17:47
  • Thanks @jcalz yes it does what I want! Just need to understand how it's actually doing it. – andre_b Nov 04 '21 at 18:22
  • Yeah, it's not pretty because it's not a simple operation to describe to the compiler; you are basically recursively walking down through the object and concatenating keys to the results of `Flatten` applied to each property, but the specifics of it are monstrous. – jcalz Nov 04 '21 at 18:30

0 Answers0