Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict enum string values in typescript

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?

like image 496
matchish Avatar asked Dec 14 '25 07:12

matchish


1 Answers

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.

like image 117
captain-yossarian Avatar answered Dec 16 '25 23:12

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!