TypeScript Enums
An enum (short for "enumerated type") is a data type that contains a finite number of allowed values, each with its own identifier. In TypeScript, an enum's values can be string
or number
.
String Enums
Consider the following enum definition.
We have named this enum Planet. It is conventional to use a capital letter for enum names. This is because, as for a class, an enum can be referenced both as a value and a type.
Enums as values
Accessing Values
We access the value "Earth"
via Planet.earth
. We use this approach in Example 1, when we are comparing the input planet
to decide which message to build.
The purpose of using an enum and not string literal values is to have a single source of truth for each value. Further, the keys of the enum (e.g. earth
in Planet.earth
are developer facing, while the values (e.g. "Earth") could potentially be user facing. If you decide later that you want to use fictional planet names in your game, you can simply change the values in one place, instead of searching and replacing "Earth" with "Crypton" across your codebase.
Iterating over all values
We sometimes need to loop over all values of the enum. We can do that using Object.entries
(...). In Example 1, we use this approach to print one message for each planet.
Enums as types
We can use Planet
as a type, as in typing the planet
parameter in the arrow function buildWelcomeMessage
. The type of an enum is the union of the types of its values. In this case, the type Planet
resolves to "Earth" | "Mars" | "Saturn"
.
typeguards
To write a typeguard for an enum, simply check if an input is one of the values of the enum, as in isPlanet
in Example 2. The typeguard is used in Example 3. Note that you will get type inference on line 3, where destination
will be a Planet
.
Bonus
I find myself exporting an enum and a corresponding typeguard every time. You could build a helper to create the typeguard as follows.