The native enum
in Typescript is considered not safe to use (see Don't use Enums in Typescript, they are very dangerous)
How can I implement a safer enum
that doesn't suffer the stated issues?
I'm new to Typescript and I was looking for something like 4 Ways to Create an Enum in JavaScript
Asking to ChatGPT it suggests this possible implementation, but I don't have the means yet to guess if it is the best one nor if it does not suffer from some arcane issue:
const MyEnum = {
MyValue1: 'value1' as const,
MyValue2: 'value2' as const,
MyValue3: 'value3' as const,
};
type MyEnum = typeof MyEnum[keyof typeof MyEnum];
Usage example:
function printMyEnum(value: MyEnum): void {
switch (value) {
case MyEnum.MyValue1:
console.log('>> MyValue1')
break;
case MyEnum.MyValue2:
console.log('>> MyValue2')
break;
case MyEnum.MyValue3:
console.log('>> MyValue3')
break;
default:
throw new Error(`Invalid value: ${value}`);
}
}
printMyEnum(MyEnum.MyValue1)
// >> MyValue1
Note: this is not a duplicate of How to create enum like type in TypeScript?, since answers to that question only report the standard Typescript enum
Thanks a lot in advance!