代码之家  ›  专栏  ›  技术社区  ›  Michael Wilson

Typescript如何提取嵌套类型

  •  0
  • Michael Wilson  · 技术社区  · 5 年前

    如何提取嵌套属性的类型?例如,假设我有这种类型:

    type Example = {
       nested: string,  // how do I infer string here
       other: string
    }
    

    这样我就可以从示例.嵌套?

    我有 type myType = Pick<Example, "nested"> 这就提供了 { nested: string } ,但我想推断该对象上属性“nested”(本例中为字符串)的类型。

    0 回复  |  直到 5 年前
        1
  •  7
  •   jcalz    5 年前

    你想使用 lookup type (也称为“索引访问类型”),它使用方括号语法。

    也就是说,

    type myType = Example["nested"] // string
    

    希望有帮助,祝你好运!

    Link to code