首页 > 解决方案 > 如何在 Typescrpt 中表达相互关联的类型层次结构

问题描述

我是 TypeScript 的新手,我正在尝试弄清楚如何最好地表达类型依赖。我正在开发具有以下层次结构的游戏:

enum Factions {
  Government,
  Intelligentsia
}

enum GovernmentTypes {
  Liberal,
  Autocratic,
  Neutral
}

enum IntelligentsiaTypes {
  Scientific,
  Religious,
  Neutral
}

interface Building {
  name: string,
  faction: Factions,
  subtype: ?--HOW-TO-EXPRESS-THIS-TYPE--?
}

我想要它,以便当建筑物的派系是:

实现这一目标的最佳方法是什么?提前致谢。

标签: typescript

解决方案


你真正想表达的是 和 之间的Factions关系***Types

我已经在Factions对象类型中捕捉到了这种关系。

以下应该以您期望的方式添加约束:

enum GovernmentTypes {
  Liberal,
  Autocratic,
  Neutral
}

enum IntelligentsiaTypes {
  Scientific,
  Religious,
  Neutral
}

type Factions = {
  Government: GovernmentTypes
  Intelligentsia: IntelligentsiaTypes
}

interface Building<T extends keyof Factions> {
  name: string
  faction: T
  subtype: Factions[T]
}

const factions1: Building<'Government'> = {
  name: 'Asd',
  faction: 'Government',
  subtype: GovernmentTypes.Autocratic
} //  compiles

const factions0: Building<'Government'> = {
  name: 'Asd',
  faction: 'Government',
  subtype: IntelligentsiaTypes.Neutral
} // does not compile



推荐阅读