Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

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"); // Okay
move(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"
}