3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can we reuse PersistentAction type to not duplicate literal strings in persistentActions?
@matchish sorry, did not understand. PersistentAction is already reused in Actions type
I mean we duplicate literal strings i.imgur.com/uI3xQeZ.png
In first case these strings are in type scope, in the second case they are values. You cant use type as value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.