首页 > 解决方案 > 我可以在 Typescript 中提取类型的嵌套结构以使用它来声明新类型吗?

问题描述

考虑如下定义的类型:

type primaryType = {
  level1: {
    level12: {
      a: string
      b: string
      c: string
    }
  }
  ... 
}

现在我想创建一个新类型,它是从带有 key 的属性中推断出来的level12,因此,它将隐含地具有属性ab并且c

// Something like this (notation is not valid, used just to visualize the idea):
type inferredType = primaryType.level1.level12

// Not this:
type inferredType = {
  a: string
  b: string
  c: string
}

我扫描了实用程序类型,但无法为此目的进行转换。

有没有办法做到这一点?

标签: typescript

解决方案


那么你可以这样做:

type inferredType = primaryType['level1']['level12']

推荐阅读