提取联合类型中属性的类型

时间:2019-03-13 07:09:52

标签: typescript union-types

我使用以下代码:

interface A {
  color: "red"
  a: string
}
interface B {
  color: "green"
  b: number
}
interface C {
  color: "blue"
  c: boolean
}

type D = A | B | C // Type is like: { color: "red" | "green" | "blue" }

declare const fakeVariable: D

type Color = typeof fakeVariable.color // Type is: "red" | "green" | "blue"

它按预期工作。但是,是否可以自动创建类型Color而无需声明假变量?

1 个答案:

答案 0 :(得分:3)

您只需要使用index type query

type Color = D['color']