Typescript — Enums Vs. Constants

Angular: The Full Gamut Edition

Charlie Greenman
August 30, 2020
2 min read

What This Is About

This article will discuss nuances between enums in Typescript, versus, regular ES6 constants. In addition, it will discuss why using enums is more convenient, and should be used in a Typescript setting.

If you are unfamiliar with the benefits of constants, feel free to take a look at the brief article here, discussing the benefits of doing so.


Constants in a Non Typescript Setting

In order to define a constant in a non-Typescript setting, we use the const declaration to define variables:

const UP =UP;
const DOWN =DOWN;
const LEFT =LEFT;
const RIGHT =RIGHT;

Enums, an Introduction

Simply put, enums allow us to define a set of named constants:

enum PlaneActionTypes {
  Up = "[Plane] Up",
  Down = "[Plane] DOWN",
  Left = "[Plane] LEFT",
  Right = "[Plane] RIGHT",
}

Benefit of Enums over Constants

Enums allow us to organize a collection of related values. Think of them as a class for values, wherein the value can only be a string , or number.


Current Quirk of String Enums

String Enums, as opposed to number Enums, have to be constant initialized with a string literal. To clarify, you might want expect the following to work:

const prefix = '[Button]';
enum Direction {
  Up = `${prefix} UP`,
  Down = `${prefix} DOWN`,
  Left = `${prefix} LEFT`,
  Right = `${prefix} RIGHT`,
}

However, this does not work, because the value within the enum is not a string literal, i.e. string only.


Convention as a Result of Quirk

As a result of quirk, we need a way of specifying that this action is happening in relation to a specific object. Even though we do have a set using enums, when identifying the string on it’s own, from a state management (dev tool) perspective, or console perspective, it will be beneficial to have the string literal be explicit on it’s own. This is therefore the recommended convention. (Please reference above subsection, “Enums as an Introduction”, for how this translates to code in principle.)

Congratulations, you are now a master at understanding the difference between enums and constants.

More articles similar to this

footer

Razroo is committed towards contributing to open source. Take the pledge towards open source by tweeting, #itaketherazroopledge to @_Razroo on twitter. One of our associates will get back to you and set you up with an open source project to work on.