Photo by Krivec Ales from Pexels

Introducing Flow Enums

George Zahariev
Sep 13 · 3 min read

As announced in an earlier post, Flow will be introducing new language features. The first one is Flow Enums, an opt-in feature which allows you to define a fixed set of constants which create their own type. If you are familiar with TypeScript, you can take a look at our comparison of Flow Enums and TypeScript enums.

Flow Enums provide several benefits over existing enum-like patterns (like Object.freeze and string literal unions): reducing repetition by defining a value and type in one definition, enabling new functionality like a type-safe cast function, enhancing safety by requiring exhaustive checking in switch statements, and guaranteeing good Flow performance.

At Facebook, we’ve been using Flow Enums for over a year, and have over 5,000 Flow Enums in our codebase.

The documentation has complete information about how to enable, define and use Flow Enums. Here is a quick overview:

Overview

Unlike other features in Flow, enums exist as values at runtime, as well as existing as types.

Define an enum with string values which mirror the member names:

Define an enum with number values:

Previously if using Object.freeze, you would have to define a object with values and a type separately, which is more verbose.

Access an enum member, and use the enum name as a type annotation:

Previously, the type name and enum object name would be different, now we can have one name and one import for both type and value.

Safely cast a string to an enum member (or undefined if not a valid member):

Previously, you would have to create a switch statement with every enum member as a case in order to cast an arbitrary string/number to an enum value in a type-safe way.

Check an enum in switch statement exhaustively - we ensure you check all members:

Flow Enums are not a syntax for union types. They are their own type, and each member of a Flow Enum has the same type. Large union types can cause performance issues, as Flow has to consider each member as a separate type. With Flow Enums, no matter how large your enum is, Flow will always exhibit good performance as it only has one type to keep track of.

Read the quickstart guide for more, and the defining enums and using enums documentation for an in-depth look.

Enabling Flow Enums

You can read the full documentation on how to enable Flow Enums in your project. In short:

Migrating Legacy Patterns

You can then migrate from legacy patterns in your codebase. For example, if before you had:

You can use:

If before you cast to the enum type like this:

You can now just use:

More

Read the documentation for more information.

Flow

The official publication for the Flow static type checker