Differences between an Enum and a Javascript object
You may wonder what benefits using an Enum has over using an object in Javascript. This is because both can solve similar problems, such as defining a finite number of options, naming values that are not very clear on their own, etc.
Validation
Let's look at the following example using an object:
ts
const Transmission = {
Automatic: 'automatic',
Manual: 'manual',
};
Transmission.Automatic = 'electric'; // 🙃 without validation
let transmission: string;
transmission = Transmission.Automatic; // 'automatic'
transmission = Transmission.Manual; // 'manual'
transmission = 'electric'; // 'electric' - 🙃 without validation
As we see in the example, using objects makes it easy for us to assign default values, but it does not allow us to validate that what we assign is within the previously defined finite values.
Now let's see the example using an Enum:
ts
enum Transmission {
Automatic = 'automatic',
Manual = 'manual',
}
// ❌ Cannot assign to 'Automatic' because it is a read-only property.
Transmission.Automatic = 'electric';
let transmission: Transmission;
transmission = Transmission.Automatic; // 'automatic'
transmission = Transmission.Manual; // 'manual'
// ❌ Type '"electric"' is not assignable to type 'Transmission'
transmission = 'electric';
When using Enum, we delegate the validation of the available options to Typescript. This can provide us with useful error messages during the development stage.