Member-only story

Here are the TypeScript Enums I Actually Want to Use

Robin Pokorny
JavaScript in Plain English

Since the very first moment I learned about TypeScript, I knew there’s gonna be this one thing I’ll always hate: Enums. So un-elegant, so old-school, and so why-do-you-pollute-my-runtime.

Well, I was wrong. I use Enums now. At least some of them.

Let me show you.

What is an Enum in TypeScript?

First, let’s quickly talk about what are Enumerators, or Enums for short.

An Enum in TypeScript is a well-defined collection of a limited number of cases. That is, we write down all possibilities and do not allow anything else.

The meaning of enumerations is that in the code you deal with only these few cases and you can be sure to deal with all of them. The compiler will warn if you forget to handle one or more.

Here are some common enumeration examples to give you a better idea:

  • Directions: North, South, East, West
  • CardRanks: Ace, King, Queen, Jack, 10, 9, 8, 7, 6, 5, 4, 3, 2
  • DateFormats: Unix, ISO, Email

In this article, I’ll be using countries my app supports as an example. This is how you write enums in TypeScript:

enum Country {
Germany,
Sweden,
USA,
}

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response