使用枚举我们可以定义一些带名字的常量。 使用枚举可以清晰地表达意图或创建一组有区别的用例。 TypeScript支持数字的和基于字符串的枚举。
数字枚举类型
会自动填充,如果为声明,默认值为0,也可以手动赋值,后续未声明的则自动递增
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
console.log(Week[0] === 'Monday') console.log(Week.Monday)
var Week; (function (Week) { Week[Week["Monday"] = 0] = "Monday"; Week[Week["Tuesday"] = 1] = "Tuesday"; Week[Week["Wednesday"] = 2] = "Wednesday"; Week[Week["Thursday"] = 3] = "Thursday"; Week[Week["Friday"] = 4] = "Friday"; Week[Week["Saturday"] = 5] = "Saturday"; Week[Week["Sunday"] = 6] = "Sunday"; })(Week || (Week = {})); console.log(Week[0] === 'Monday'); console.log(Week.Monday)
enum Week { Monday = 1, Tuesday, Wednesday, Thursday, Friday = 8, Saturday, Sunday }
console.log(Week[0] === 'Monday')
var Week; (function (Week) { Week[Week["Monday"] = 1] = "Monday"; Week[Week["Tuesday"] = 2] = "Tuesday"; Week[Week["Wednesday"] = 3] = "Wednesday"; Week[Week["Thursday"] = 4] = "Thursday"; Week[Week["Friday"] = 8] = "Friday"; Week[Week["Saturday"] = 9] = "Saturday"; Week[Week["Sunday"] = 10] = "Sunday"; })(Week || (Week = {})); console.log(Week[0] === 'Monday');
|
常数项和计算所得项
枚举项有两种类型:常数项和计算所得项。
1 2 3 4 5
| enum Color { Red, Green, Blue = 'blue'.length }
|
blue’.length为计算所得项。
如果紧接着计算所得项继续添加枚举项,会因为无法获得初始值而报错。
1 2 3 4 5 6
| enum Color { Red, Green, Blue = 'blue'.length, Grey }
|
字符串枚举
在一个字符串枚举里,每个成员都必须用字符串字面量,或另外一个字符串枚举成员进行初始化。
由于字符串枚举没有自增长的行为,字符串枚举可以很好的序列化。
1 2 3 4 5 6
| enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT", }
|