Hacker News new | ask | show | jobs
by MBCook 478 days ago
What do people find works better as a string enum replacement?

  const Thing {
    one: “one”,
    two: “two”,
    three: “three”
  } as const
Or just

  type Thing = “one” | “two” | “three”
I’ve been thinking of getting rid of the simple string enums I have but it’s not clear to me why one is preferred over the other by people.
2 comments

If all you need is a union type then the latter is plenty.

If you need the actual strings to iterate over or validate against, deriving the value from an const array is helpful:

  const THINGS = ['one', 'two', 'three'] as const

  type Thing = THINGS[number]
If you want to be able to use the syntax

    Thing.one
or

    Thing.two
while having each refer to a discrete symbol, you should probably use Symbols

so:

    const Thing = {
      one: Symbol(),
      two: Symbol()
    } as const;
will prevent anything equality matching that isn't intentional