Ts-Enums
A TypeScript library for enums, inspired by Java enums and forked from Enumify.
Motivation
Dr. Axel Rauschmeyer created Enumify to bring an analogue of Java's Enums to JavaScript. In a blog post, he explained why a naive implementation of enums in JavaScript lacks the power of Java Enums.
TypeScript Enums provide a start to a Java-style Enum implementation, but they lack the killer feature of Java's Enum: classes. Java's Enums are full classes, enabling properties and methods (including abstract methods and overriding within an enum). In contrast, TypeScript enums are limited to being namespaced integers or strings.
Enumify is a strong introduction to class-style enums in JavaScript, and this project ports the idea to TypeScript. This port loses the feature from Enumify of creating an enumeration from an array of Strings, but string-based TypeScript enums were added in 2.4.1, so that is not a large loss.
The basics
Install:
npm install ts-enums
Use:
; ; // examples of useconsole.logColorEnum.RED.toString; // Color.REDconsole.logColorEnum.GREEN instanceof Color; // true new Color; // Error: EnumValue classes can’t be instantiated individually
Unfortunately, this is not as terse as Enumify's syntax. Here are the steps:
- We define the implementation of EnumValue that defines each of the instances.
- We implement each instance of the EnumValue as a property on the Enum. Within the Enum, we call
initEnum()
with a unique name to set up all of the Enum-specific behavior. - We export an instance of the enum so that other modules can use it.
Properties of Enum classes
Enum exposes the getter values
, which produces an Array with all enum values:
for of ColorEnum.values // Output:// Color.RED// Color.GREEN// Color.BLUE
Enum exposes the methods byPropName
and byDescription
, to extract the EnumValue instance by either the property name of the object in the Enum or the description string passed into the EnumValue's constructor, respectively:
console.logColorEnum.byPropName'RED' === ColorEnum.RED; // trueconsole.logColorEnum.byDescription'RED name' === ColorEnum.RED; // truetrue
Properties of enum values
Ts-Enums adds two properties to every enum value:
-
propName
: the property name of the object in the Enum.> ColorEnum.BLUE.name'BLUE' -
ordinal
: the position of the enum value within the Arrayvalues
.> ColorEnum.BLUE.ordinal2
Adding properties to enum values
The EnumValues are full TypeScript classes, enabling you to add properties and methods (see the tests for more examples).
;; ; console.logBridgeSuitEnum.HEARTS.color.toString; // Color.REDconsole.logBridgeSuitEnum.HEARTS.isMajor; // true// ``` ## More information * The directory test contains examples.* See https://github.com/LMFinney/ngrx-example-app-enums) for a more complicated implementation supporting an [@ngrx](https://github.com/ngrx/store) app.