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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
// 数字枚举
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction.Up === 0); // true
console.log(Direction.Down === 1); // true
console.log(Direction.Left === 2); // true
console.log(Direction.Right === 3); // true
// 把第一个值赋值后,后面也会根据第一个值进行累加
enum Direction {
Up = 10,
Down,
Left,
Right
}
console.log(
Direction.Up, // 10
Direction.Down, // 11
Direction.Left, // 12
Direction.Right // 13
);
// 字符串枚举
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
console.log(
Direction['Right'], // Right
Direction.Up // Up
);
// 异构枚举
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = 'YES'
}
// 反向映射 name <=> value
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction[0]); // Up
// 枚举的本质
var Direction;
(function (Direction) {
Direction[(Direction['Up'] = 10)] = 'Up';
Direction[(Direction['Down'] = 11)] = 'Down';
Direction[(Direction['Left'] = 12)] = 'Left';
Direction[(Direction['Right'] = 13)] = 'Right';
})(Direction || (Direction = {}));
// 联合枚举与枚举成员的类型
enum Direction {
Up,
Down,
Left,
Right
}
const va = 0;
console.log(va === Direction.Up); // true
type vc = 0;
declare let vb: vc;
vb = 1; // fault
vb = Direction.Up; // pass
// 联合枚举类型
enum Direction {
Up,
Down,
Left,
Right
}
declare let a: Direction;
enum Animal {
Dog,
Cat
}
a = Direction.Up; // pass
a = Animal.Dog; // fault
// 枚举合并
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
enum Direction {
Center = 1
}
// 转换为 JS 后
var Direction;
(function (Direction) {
Direction['Up'] = 'Up';
Direction['Down'] = 'Down';
Direction['Left'] = 'Left';
Direction['Right'] = 'Right';
})(Direction || (Direction = {}));
(function (Direction) {
Direction[(Direction['Center'] = 1)] = 'Center';
})(Direction || (Direction = {}));
// 为枚举添加静态方法(借助命名空间)
enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
namespace Month {
export function isSummer(month: Month) {
switch (month) {
case Month.June:
case Month.July:
case Month.August:
return true;
default:
return false;
}
}
}
console.log(Month.isSummer(Month.January)); // false
|