打字稿如何提取嵌套类型

Mic*_*son 6 typescript

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

type Example = {
   nested: string,  // how do I infer string here
   other: string
}
Run Code Online (Sandbox Code Playgroud)

这样我就可以从 Example.nested 中提取出“字符串”?

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

jca*_*alz 14

您想使用使用方括号语法的查找类型(也称为“索引访问类型”)。

那是,

type myType = Example["nested"] // string
Run Code Online (Sandbox Code Playgroud)

希望有所帮助;祝你好运!

代码链接

  • 如果它是可选密钥怎么办? (11认同)
  • 仅供参考:如果嵌套类型是数组,并且您想要数组中条目的类型,则语法为“Example["nested"][0]”。 (2认同)