【问题标题】:Type-safe Enum Dictionaries in TypescriptTypescript 中的类型安全枚举字典
【发布时间】:2020-12-30 05:35:07
【问题描述】:

我希望 dirVectors[Turn.Straight] 在编译时失败。

enum Direction {
    Up,
    Down,
    Right,
    Left,
}

enum Turn {
    Clockwise,
    Counterclockwise,
    Straight,
}

const dirVectors = {
    [Direction.Up]: [0, 1],
    [Direction.Down]: [0, -1],
    [Direction.Right]: [1, 0],
    [Direction.Left]: [-1, 0]
} as Record<Direction, [number, number]>;

我假设dirVectors[Turn.Straight] 可以的原因是因为它们都是数字,Straight = 2Direction {0,...,3} 的子集。当我为每个枚举的值分配一个唯一的字符串时,它确实在编译时失败。但是,是否有可能在不走字符串路由的情况下得到编译时错误?

【问题讨论】:

  • 如果两个枚举条目具有相同的值,它们可以互换使用来索引Record。如果不为每个枚举条目分配一个全局唯一值,我认为无论如何都无法改变它。

标签: typescript


【解决方案1】:

如果你给 Enum 赋值,它会按预期工作:

enum Direction {
  Up = 'Up',
  Down = 'Down',
  Right = 'Right',
  Left = 'Left'
}

enum Turn {
  Clockwise = 'Clockwise',
  Counterclockwise = 'Counterclockwise',
  Straight = 'Straight'
}

const dirVectors = {
  [Direction.Up]: [0, 1],
  [Direction.Down]: [0, -1],
  [Direction.Right]: [1, 0],
  [Direction.Left]: [-1, 0]
} as Record<Direction, [number, number]>

dirVectors[Direction.Up] // compiles
dirVectors[Turn.Straight] // does not compile

问题是,你真的需要 Enum 吗?您是否使用了 Enum 中联合类型不提供的任何内容? 看看以下是否适合您:

type Direction = 'Up' | 'Down' | 'Right' | 'Left'

type Turn = 'Clockwise' | 'Counterclockwise' | 'Straight'

const dirVectors: Record<Direction, [number, number]> = {
  Up: [0, 1],
  Down: [0, -1],
  Right: [1, 0],
  Left: [-1, 0]
}

dirVectors['Down'] // compiles
dirVectors['Straight'] // does not compile

【讨论】:

  • However, is it possible to get the compile-time error without going the string route?提出的问题
  • 是的,包括其他方法!
  • 我一直认为枚举比联合类型更受欢迎,因为命名空间以及它们在其他语言中的普遍流行。 stackoverflow.com/questions/40275832 深入探讨了为什么不是这样。我将开始使用联合类型。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多