TypeScript 枚举(Enum)
本节介绍枚举类型的定义及其使用,需要定义一组相同主题的常量数据时,应该立即想到枚举类型。在学习过程中,需要注意枚举类型的正向映射和反向映射,可以通过编译后的 JavaScript 源码进行分析,为什么可以进行反向映射。
1. 解释
使用枚举我们可以定义一些带名字的常量。TypeScript 支持数字的和基于字符串的枚举。
2. 定义及使用场景
枚举类型弥补了 JavaScript 的设计不足,很多语言都拥有枚举类型。
当我们需要一组相同主题下的数据时,枚举类型就很有用了。
enum Direction { Up, Down, Left, Right }
enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
enum Size { big = '大', medium = '中', small = '小' }
enum Agency { province = , city = , district = }
代码解释:
3. 数字枚举与字符串枚举
enum Months {
Jan,
Feb,
Mar,
Apr
}
Months.Jan === // true
Months.Feb === // true
Months.Mar === // true
Months.Apr === // true
现实中月份是从 1 月开始的,那么只需要这样:
// 从第一个数字赋值,往后依次累加
enum Months {
Jan = ,
Feb,
Mar,
Apr
}
Months.Jan === // true
Months.Feb === // true
Months.Mar === // true
Months.Apr === // true
代码解释:
枚举类型的值为字符串类型:
数字类型和字符串类型可以混合使用,但是不建议:
enum BooleanLikeHeterogeneousEnum {
No = ,
Yes = "YES",
}
4. 计算常量成员
枚举类型的值可以是一个简单的计算表达式:
Tips:
- 计算结果必须为常量。
- 计算项必须放在最后。
5. 反向映射
所谓的反向映射就是指枚举的取值,不但可以正向的 Months.Jan
这样取值,也可以反向的 Months[1]
这样取值。
enum Months {
Jan = ,
Feb,
Mar,
Apr
}
'use strict'
var Months;
(function (Months) {
Months[Months['Jan'] = ] = 'Jan'
Months[Months['Feb'] = ] = 'Feb'
Months[Months['Mar'] = ] = 'Mar'
Months[Months['Apr'] = ] = 'Apr'
})(Months || (Months = {}))
通过查看编译后的代码,可以得出:
console.log(Months.Mar === ) // true
// 那么反过来能取到 Months[3] 的值吗?
console.log(Months[]) // 'Mar'
// 所以
console.log(Months.Mar === ) // true
console.log(Months[] === 'Mar') // true
Tips:
6. const 枚举
在枚举上使用 const
修饰符:
enum Months {
Jan = ,
Feb,
Mar,
Apr
}
const month = Months.Mar
查看一下编译后的内容:
'use strict'
const month = /* Mar */
发现枚举类型应该编译出的对象没有了,只剩下 month
常量。这就是使用 const
关键字声明枚举的作用。因为变量 month
已经使用过枚举类型,在编译阶段 TypeScript 就将枚举类型抹去,这也是性能提升的一种方案。
7. 枚举合并
enum Months {
Jan = ,
Feb,
Mar,
Apr
}
enum Months {
May = ,
Jun
}
console.log(Months.Apr) // 4
console.log(Months.Jun) // 6
编译后的 JavaScript 代码:
'use strict'
var Months;
(function (Months) {
Months[Months['Jan'] = ] = 'Jan'
Months[Months['Feb'] = ] = 'Feb'
Months[Months['Mar'] = ] = 'Mar'
Months[Months['Apr'] = ] = 'Apr'
})(Months || (Months = {}));
(function (Months) {
Months[Months['May'] = ] = 'May'
Months[Months['Jun'] = ] = 'Jun'
})(Months || (Months = {}))
console.log(Months.Apr) // 4
console.log(Months.Jun) // 6
8. 小结
通过本节的介绍需要知道:
- 通过关键字
enum
来声明枚举类型。 - TypeScript 仅支持基于数字和字符串的枚举。
- 通过枚举类型编译后的结果,了解到其本质上就是 JavaScript 对象。