简体   繁体   English

Typescript 中的类型安全枚举字典

[英]Type-safe Enum Dictionaries in Typescript

I would like dirVectors[Turn.Straight] to fail at compile-time.我希望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]>;

I'm assuming the reason dirVectors[Turn.Straight] is OK is because they're both numbers, with Straight = 2 , which is a subset of Direction {0,...,3} .我假设dirVectors[Turn.Straight]的原因是因为它们都是数字, Straight = 2 ,它是Direction {0,...,3}的子集。 When I assign a unique string to each enum's value, it does fail at compile-time.当我为每个枚举的值分配一个唯一的字符串时,它确实在编译时失败。 However, is it possible to get the compile-time error without going the string route?但是,是否有可能在不使用字符串路由的情况下获得编译时错误?

If you assign values to Enum, it works as expected:如果您为 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

Question is, do you really need Enum?问题是,你真的需要 Enum 吗? Are you using anything from Enum which union types does not provide?您是否使用 Enum 中联合类型不提供的任何内容? See if following works for you:看看以下是否适合您:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM