1

Given the following sturcture:

type Structure = {
  parent1: {
    child1_1: true,
    child1_2: true
  },
  parent2: {
    child2_1: true,
    child2_2: true
  }
}

I want to infer the following type:

// Expected result: 
type FlattenedStructure = "parent1.child1_1" | "parent1.child1_2" | "parent2.child2_1" | "parent2.child2_2"

I tried to:

// Expected result: type FlattenedStructure = "parent1.child1_1" | "parent1.child1_2" | "parent2.child2_1" | "parent2.child2_2"
type FlattenedStructure<T extends Structure = Structure> = {
  [parent in keyof T]: `${parent}.${keyof T[parent]}`
}[keyof T];


// I'm aware of this approach, but I'm not trying to do it this way
const getChild = <P extends keyof Structure, C extends keyof Structure[P]>(parent: P, child: C) => {
  return `${parent}.${child}` as const;
}

const b = getChild("parent2", "child2_1");

but it looks like I'm missing something. Autogenerate this combination would be the last resort if it's not possible.

See playground

PS - I'm aware of the question Inferring types of deeply nested object in Typescript but my use case is different.

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
  • You can use [this code](https://tsplay.dev/w26o1w) to get a union of dotted paths in an object type. See [the question this duplicates](https://stackoverflow.com/questions/58434389/typescript-deep-keyof-of-a-nested-object) for more info. – jcalz Apr 25 '21 at 19:01

0 Answers0