如何通过嵌套对象推断类型

时间:2021-04-25 18:32:21

标签: typescript

鉴于以下结构:

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

我想推断以下类型:

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

我试图:

// 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");

但是我好像遗漏了什么。如果不可能,自动生成此组合将是最后的手段。

See playground

PS - 我知道问题 Inferring types of deeply nested object in Typescript,但我的用例不同。

0 个答案:

没有答案