学习
实践
活动
专区
工具
TVP
写文章

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

浏览 59关注 0回答 1得票数 1
原文

我有可能有行动价值的类型

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

然后,我想用动作来定义枚举

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

如何将枚举值限制为PersistentAction?也许枚举的类型不适合它?

原文
Stack Overflow用户提问于2020-11-06 13:58

1 个回答

高票数最新
Stack Overflow用户
修改于2020-11-06 16:35
已采纳
得票数 2

枚举只能存储静态值。

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

请记住,它只适用于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

但在上面的情况下,你应该小写你的键。

页面原文内容由stack overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:https://stackoverflow.com/questions/64709580复制

扫码关注腾讯云开发者

领取腾讯云代金券