2 ms·
What do people find works better as a string enum replacement? const Thing { one: “one”, two: “two”, three: “three” } as const Or just type
by MBCook 2y 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.
- braebo 2y agoIf 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]
- pcthrowaway 2y agoIf 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