Skip to content
A simple function for creating enum object in javascript. Won't break your flowtypes.
Branch: master
Clone or download
ryan953 Merge pull request #54 from ryan953/greenkeeper/flow-bin-0.108.0
chore(package): update flow-bin to version 0.108.0
Latest commit 193a661 Oct 2, 2019


Current Version Build Status Greenkeeper badge

Create an enum from a object of key/values.

Install with npm.

# Capitalization matters!
npm install Enumjs --save

Use with node.js, browserify or webpack, etc:

var Enum = require('Enumjs');

Or you can use a <script> tag to include the index.js and it will create a global Enum object, or define that object for require.js if it exists.


Once the package is installed you can create instances by passing the key/value object to the constructor.

var Enum = require('Enumjs');

const Suits = Enum.make({

Your new Enum is a plain object that's been frozen so no one can edit the fields or values on it. It is enumerable, immutable, and you can use the in operator, hasOwnProperty() just like normal.

console.log('HEART' in Suits)
-> true
-> true
-> 'HEART'
-> 'HEART'
-> 4

Also provided are helper methods Enum.coalesce(enum: Enum, field: string) and Enum.enforce(enum: Enum, field: string). Each of these test whether the field provided is a member of the enum and return the value if it is. If the value is not a member then coalesce returns null, while enforce throws an error.

console.log(Enum.coalesce(Suits, 'HEART'))
-> 'HEART'
console.log(Enum.coalesce(Suits, 'foobar'))
-> null
console.log(Enum.enforce(Suits, 'SPADE'))
-> 'SPADE'
console.log(Enum.enforce(Suits, 'bizbaz')) // throws Error

Flow Types

Configure flow by adding the path to Enumjs/interfaces into your .flowconfig file:


To turn Enum objects into flow types simply create a flow type using the $Keys feature:

type SuitType = $Keys<typeof Suits>;

If your values are not the same as the keys then you can use $Keys and $Values to differentiate between the two sets:

type SuitType = $Keys<typeof Suits>;
type SuitValue = $Values<typeof Suits>;


Within index.js some new methods are used that are not available on older browsers. See Object.create Object.entries Object.freeze Object.values

Unit Tests: The tests also requires Object.keys.

You can’t perform that action at this time.