1

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!

Caliuf
  • 63
  • 6
  • 1
    Your ChatGPT-generated code looks fine to me, and something very similar is written in the article you quote at the beginning. I've linked to another question asking about differences between native enums and the `as const` solution as described here. – jcalz Apr 22 '23 at 13:28
  • Enums define both a type and a value with the same name, and they do it differently than classes which is the only other TS construct that does so. In theory something like [this code](https://www.typescriptlang.org/play?#code/PTAEBEFMDMEsDtKgEYHsAuALUBDU6BPAB0gDpyAoQk0AWQIFF4BXAW1AF5QBvC0XAFygAjHxRCATGIDGQgMwUAvhQohQ5UjngATXKABuOADbMkqaKADOOVkng3IFaaniX0dRi1ZD6TNpx4xHCFhABoxZElw-llQOXDFXEtQZ1d0FWhmeGl0WBdQaFRUAAoADx9PNgBKHmVUt1BSgN8vKmIkABUA6khzRs1QNR6RJNBIUpIcyG0KQpKWtk0atWRmd0tUW0xUAHdQTEgAJyRYZLwvZCOAfhVxolRD915+UqUKIA) should work, but you can see that it doesn't. – Jared Smith Apr 22 '23 at 13:35
  • 1
    Honestly I just use the standard enums but with awareness of the limitations and caveats. That article overstates the impact of the issues with them IMHO, but it's the internet: they gotta get clicks somehow. – Jared Smith Apr 22 '23 at 13:36

0 Answers0