Enum or const
Enum's are fine
I've been using enum for a long time and tried switching to const several times. For the most part, there's very little syntax and not many downsides so long as the enums are assigned a value.
enum StatusAsEnum { Active = 'active', Deactive = 'deactive', None = 'none',}
const better?
The flip side of this is to define a const as const
and then use a keyof to get the type.
const Status = { Active: 'Active', Deactive: 'Deactive', None: 'None',} as consttype StatusAsConst = keyof typeof statusfunction log(status: StatusAsConst) { if (status === status.Active) { console.log('We are active') } console.log(status)}
This is ok but now we need the
a) const as const declaration
b) keyof typeof
syntax, a secondary type declaration and then we also need to ensure that our key/value's are actually identical when we want to use them.
Using this other syntax is probably just laziness on my part. It's always required importing both the type and the const and knowing which is which when checking against. Not having a naming standard for these PascalCase'd const's. It was kind of nice that things that are typescript are PascalCase'd.
Maybe I'll try again in 2023 and see if I can get used to it since it's closer to js.
Alternative as const
This way we use the as const
syntax and then use the typeof
to get the type. Then we can use the const enum when we need to provide the type.
const PUSHER_STATUS = { INITIALIZED: 'initialized', CONNECTING: 'connecting', CONNECTED: 'connected', UNAVAILABLE: 'unavailable', FAILED: 'failed', DISCONNECTED: 'disconnected', //...} as consttype PusherStatus = (typeof PUSHER_STATUS)[keyof typeof PUSHER_STATUS]// type PusherStatus = 'uninitialized' | 'connecting' | 'connected' | 'unavailable' | 'failed' | 'disconnected'function exampleStatus({ status }: { status: PusherStatus }) { if (status === PUSHER_STATUS.CONNECTED) { console.log('We are connected') } else { //... }}
Conclusion
Making this into a utility may make it easier to remember.
type Values<T> = T[keyof T]
utility-types
has this included as
import { $Values } from 'utility-types'type PusherStatus = $Values<typeof PUSHER_STATUS>