How to Convert an Enum to a Number in TypeScript

To convert an enum to a number in TypeScript, you can use type casting or explicit value assignment. Here are a few examples:

  1. 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.

  1. 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.

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-01-26 01:18:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-26 01:18:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-26 01:18:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-26 01:18:01       20 阅读

热门阅读

  1. LeetCode 2865. 美丽塔 I,前后缀分离+单调栈

    2024-01-26 01:18:01       36 阅读
  2. 《深度解析Docker命令:从入门到高级应用》

    2024-01-26 01:18:01       29 阅读
  3. Vue3组件通信相关内容整理

    2024-01-26 01:18:01       38 阅读
  4. 5G_射频测试_接收机测量(五)

    2024-01-26 01:18:01       26 阅读
  5. Leetcode724.寻找数组的中心索引

    2024-01-26 01:18:01       33 阅读
  6. Typescript的一些总结和部分代码

    2024-01-26 01:18:01       35 阅读
  7. 26.删除排序数组中的重复项(力扣LeetCode)

    2024-01-26 01:18:01       32 阅读
  8. AndroidStudio 无法打开 arb 文件

    2024-01-26 01:18:01       38 阅读