如何使 Typescript 接口属性依赖于另一个属性

时间:2021-07-26 19:08:25

标签: typescript

举个例子:

type Colors = {
  light: 'EC3333' | 'E91515'
  dark: '#100F0F' | '140F0F' 
}

interface Palette {
  colorType: keyof Colors
  color: Colors[keyof Colors]
}

有没有办法让 color 属性的类型依赖于 colorType 属性?

意思 - 当我选择 colorType light 时,color type 应该变成 'EC3333' | 'E91515'

1 个答案:

答案 0 :(得分:3)

您不能将 Palette 表示为单个非泛型 interface,但您可以将其设为 colorType 和 {{1} 的每个所需配对的 union }}:

color

您甚至可以通过 mapping over type Palette = { colorType: "light"; color: "EC3333" | "E91515"; } | { colorType: "dark"; color: "#100F0F" | "140F0F"; } 的键,然后立即 indexing 到生成的映射对象类型,让编译器从 Colors 为您计算:

Colors

您可以通过 IntelliSense 验证这会产生与以前相同的类型,优点是如果您更改 type Palette = { [K in keyof Colors]: { colorType: K color: Colors[K] } }[keyof Colors]; ,它将自动更新。


有了这种联合类型,您就可以开始使用 Colors 并看到强制执行和理解的约束:

Palette

Playground link to code