typescript - 如何在 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--?
}
我想要它,以便当建筑物的派系是:
- Government - 子类型仅限于 GovernmentTypes
- Intelligentsia- 子类型仅限于 IntelligentsiaTypes
实现这一目标的最佳方法是什么?提前致谢。
解决方案
你真正想表达的是 和 之间的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
推荐阅读
- questdb - 如何避免 QuestDB 中出现“无法乱序插入行”错误?
- angular - 我无法安装 ngx-gallery
- python - 模块文件如何从列表中接收输入?
- java - 在运行时 Java 将对象转换为其特定类型
- python - Python 通过 POST 接收 HTTP 文件
- r - R:获取错误(as.character(FUN),mode =“function”,envir = envir):
- image - unity texture2d getPixel 返回错误的颜色
- python - django/react 检索和播放音频文件
- python - 如何计算此 DFS 代码的时间复杂度?
- python - 如何在 MacOS 上正确安装和运行 virtualenv