Problem: When the left and right side match, a TypeScript enum or const...


Problem: When the left and right side match, a TypeScript enum or const object is needlessly verbose.

Solution: Use a union.

Common concern: But what if I need to iterate over the values at runtime?

Derive the union from a const array:

const statuses = ["idle", "loading"] as const

type Status = typeof statuses[number]
Common concern: But what if I need to rename a union value?

Hit F2. A union’s value can typically be safely renamed.
Concern: A union means I'm passing strings around.

No, you're passing a union type. The union constrains the potential values, and provides a clearly named type for the set of values.

It's like a lighter weight enum without a redundant key/value pair.

View original on X