top | item 42769464

(no title)

eeue56 | 1 year ago

I would do this instead:

  type MyEnum = {
    active: 0;
    inactive: 1;
  }

  const MyEnum: MyEnum = {
    active: 0, 
    inactive: 1,
  }

  const showAge = MyEnum.active;
  const showPets = MyEnum.inactive;

It's slightly more duplication, but a lot more readable (imo) to those unfamiliar to utility types. TypeScript also enforces keeping them in sync.

discuss

order

mistercow|1 year ago

That doesn't give you a type that you can use for the actual enum values. If you wanted a function argument to take in one of your enum values, you'd still have to use keyof in the signature like:

   function doSomethingWithMyEnum(val: MyEnum[keyof MyEnum])
You could do `val: number`, but now you're allowing any number at all.

Ultimately, the type syntax in TypeScript is a key part of the language, and I don't think it's unreasonable to expect developers to learn the basic typeof and keyof operators. If we were talking about something wonkier like mapped types or conditional types, sure, it might make sense to avoid those for something as basic as enums.