If you use immutable-js
and flow
in your projects, you can have statically type-checked Enums. This means you’ll get errors right in your editor and on CI if you try to access an Enum property that is misspelled or doesn’t exist.
Record
is a data type that enforces a specific set of allowed string keys on its instances. Once you define what a record consists of, it’s not possible to set unexpected properties on that record instance.
Record also allows access to its keys using common dot notation:
Let’s create a simple Enum factory:
That’s fine, but sometimes I need helper methods on an enum instance. For example, sometimes I need to get an array of all of the enum’s defined items. Other times, I might need to find the item by the value
key, e.g.:
Luckily, you can extend the Record class and add custom methods to it:
This is how it works in the end:
P.S. The examples above work with immutable@3.8.1
. Typedefs in Immutable v4 (RC at the moment) were significantly improved, but are still in flux for the extended records. Hopefully, these issues will be resolved soon!