When it comes to defining a variable with a predefined set of values in TypeScript code, there are two approaches - using an enum or using a union.
For instance, imagine we have a button with various variants such as primary, secondary, and tertiary.
We can use an enum like this:
enum ButtonVariant {
Primary = "PRIMARY",
Secondary = "SECONDARY",
Tertiary = "TERTIARY"
}
const props = defineProps({
variant: {
type: String as PropType<ButtonVariant>
}
})
<MyButton :variant="ButtonVariant.Primary" />
Alternatively, we could achieve the same result using a union:
type ButtonVariant = "PRIMARY" | "SECONDARY" | "TERTIARY";
const props = defineProps({
variant: {
type: String as PropType<ButtonVariant>
}
})
<MyButton :variant="PRIMARY" />
So, what exactly sets these two methods apart? Which approach is more preferable? When should you opt for an enum over a union, and vice versa?