访问对象值和数组成员

我们知道在 js 里我们可以通过 . 来访问对象属性,可以通过数组的下标访问数组的成员,而在 TS 中我们可以更灵活得访问类型成员。 我们可以通过单个 key 来获取对象具体属性的类型,同时我们也可以设置多个key来获取多个属性的联合类型:

interface ColorVariants {
  primary: "blue",
  secondary: "red",
  tertiary: "green"
}

type PrimaryColor = ColorVariants["primary"]
// type PrimaryColor = "blue"

type NonPrimaryColor = ColorVariants["secondary" | "tertiary"]
// type NonPrimaryColor = "red" | "green"

type EveryColor = ColorVariants[keyof ColorVariants]
// type EveryColor = "blue" | "red" | "green"

我们也可以通过设置多个数组下标来获取数组成员类型的联合类型

type Letters = ["a", "b", "c"]
// type Letters = ["a", "b", "c"]

type AOrB = Letters[0 | 1]
// type AOrB = "a" | "b"

type Letter = Letters[number]
// type Letter = "a" | "b" | "c"

在线试一试