如何限制打字稿中的枚举字符串值

时间:2020-11-06 05:58:03

标签: typescript enums

我有可能采取行动的类型

type PersistentAction = 'park' | 'retry' | 'skip' | 'stop'

然后我想用动作定义枚举

enum persistentActions {
  PARK = 'park' ,
  RETRY = 'retry', 
  SKIP = 'skip',
  STOP = 'stop',
}

如何将枚举值限制为PersistentAction? 也许枚举类型错误吗?

1 个答案:

答案 0 :(得分:1)

枚举只能存储静态值。

您可以使用常量对象代替枚举。

请记住,它仅适用于TS> = 4.1

type PersistentAction = 'park' | 'retry' | 'skip' | 'stop'

type Actions = {
   readonly [P in PersistentAction as `${uppercase P}`]:P
}

const persistentActions: Actions = {
  PARK : 'park',
  RETRY : 'retry', 
  SKIP : 'skip',
  STOP : 'stop',
} as const

如果您不能使用TS 4.1,我认为下一个解决方案值得一提:

type Actions = {
  readonly [P in PersistentAction]: P
}

const persistentActions: Actions = {
  park: 'park',
  retry: 'retry',
  skip: 'skip',
  stop: 'stop',
} as const

但是在以上情况下,您应该小写密钥。