To convert an enum to a number in TypeScript, you can use type casting or explicit value assignment. Here are a few examples:
- Type Casting:
enum Color {
Red,
Green,
Blue,
}
const color: Color = Color.Red;
const colorNumber: number = color as number;
console.log(colorNumber); // Output: 0
In this example, we have an enum called Color
with three members: Red
, Green
, and Blue
. We assign the Color.Red
member to the color
variable. By using type casting (as number
), we can convert the color
enum member to a number. The colorNumber
variable will have the value 0
when logged to the console.
- Explicit Value Assignment:
enum Color {
Red = 1,
Green = 2,
Blue = 3,
}
const color: Color = Color.Red;
const colorNumber: number = color;
console.log(colorNumber); // Output: 1
In this example, we assign explicit numeric values to the enum members. The Color.Red
member is assigned the value 1
. When we assign the color
enum member to the colorNumber
variable, TypeScript automatically assigns the corresponding numeric value. The colorNumber
variable will have the value 1
when logged to the console.
Please note that when converting an enum to a number, the default behavior is to assign numeric values starting from 0
for the first enum member and incrementing by 1
for each subsequent member. However, you can explicitly assign custom numeric values to enum members as shown in the second example.