我有可能有行动价值的类型
type PersistentAction = 'park' | 'retry' | 'skip' | 'stop'
然后,我想用动作来定义枚举
enum persistentActions {
PARK = 'park' ,
RETRY = 'retry',
SKIP = 'skip',
STOP = 'stop',
}
如何将枚举值限制为PersistentAction
?也许枚举的类型不适合它?
枚举只能存储静态值。
你可以使用常量对象代替枚举。
请记住,它只适用于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
但在上面的情况下,你应该小写你的键。