I have type with possible value of action
type PersistentAction = 'park' | 'retry' | 'skip' | 'stop'
Then I want to define enum with actions
enum persistentActions {
PARK = 'park' ,
RETRY = 'retry',
SKIP = 'skip',
STOP = 'stop',
}
How to restrict enum values to PersistentAction?
Maybe enum is wrong type for it?
Enums can store only static values.
You can use constant object instead of enums.
Please keep in mind, it works only in 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
If you can't use TS 4.1, I think next solution worth mentioning:
type Actions = {
readonly [P in PersistentAction]: P
}
const persistentActions: Actions = {
park: 'park',
retry: 'retry',
skip: 'skip',
stop: 'stop',
} as const
But in above case, You should lowercase your keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With