In my recent studies, I came across a recommendation to avoid using the built-in enum
feature in TypeScript. Instead, the suggestion was to define custom enums as follows:
const MyEnum = {
name: 'name',
email: 'email'
} as const;
type MyEnum = keyof typeof MyEnum;
The advantages of this approach are clear:
- Having
MyEnum.name
available for use wherever aMyEnum
argument is expected. - Using string literals like
'name'
without needing to importMyEnum
. - Preventing both key and value types from being included in the output of
Object.keys(MyEnum)
whenMyEnum
contains numbers instead of strings.
While I appreciate these benefits, the current implementation still requires defining a string literal for each key. I'm curious if there's a way to avoid this. For instance, could we create an enum using an array like ['name', 'email']
?