- 课程名称:Vue3 + Typescript 从0到1开发通用基础组件
- 章节名称:
- 第2章:你好Typescript:进入类型的世界
- 2-11:枚举(Enum)
- 第2章:你好Typescript:进入类型的世界
- 讲师姓名:张轩
- 时间:2022-11-04 21:38
课程内容
-
定义方法
enum Direction { Up, Down, Left, Right } console.log(Direction.Up)// 输出0 console.log(Direction[0])// 输出Up enum Direction1 { Up = 10,// 设置起始值 Down, Left, Right } // 字符串枚举 enum Direction2 { Up = 'UP', Down = 'DOWN', Left = 'LEFT', Right = 'RIGHT' } console.log(Direction2.Up)// 输出UP console.log(Direction2['Up'])// 输出UP // console.log(Direction2[0])// 报错,没有索引0,索引改为UP了 // 常量枚举,可以提升性能 const enum Direction3 { Up = 'UP', Down = 'DOWN', Left = 'LEFT', Right = 'RIGHT' }// 使用const编译成js代码非常简单,把枚举值做为单一值用在使用的地方 // 不会把枚举的定义内容编译为JS代码
课程收获
在本堂课最后,老师提到了枚举分为常量枚举,是可以使用const来优化的,但计算枚举就不行,至于为什么,留待以后分解