Enumerations

Enumerations allow us to define a set of named constants. Since the TypeScript 2.4 release, these named constant values can be string values. Originally, they could only be numeric values:

enum CardinalDirection {    Up,    Down,    Left,    Right}

A common workaround to this limitation was the usage of union types of literal types:

type CardinalDirection =    "North"    | "East"    | "South"    | "West";function move(distance: number, direction: CardinalDirection) {    // ...}move(1,"North"); // Okaymove(1,"Nurth"); // Error!

Since the TypeScript 2.4 release, enumerations with string values are also supported:

enum CardinalDirection {    Red = "North",    Green = "East",    Blue = "South",    West = "West"}

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.