1 | # `prefer-enum-initializers`
|
2 |
|
3 | Prefer initializing each enums member value.
|
4 |
|
5 | This rule recommends having each `enum`s member value explicitly initialized.
|
6 |
|
7 | `enum`s are a practical way to organize semantically related constant values. However, by implicitly defining values, `enum`s can lead to unexpected bugs if it's modified without paying attention to the order of its items.
|
8 |
|
9 | ## Rule Details
|
10 |
|
11 | `enum`s infers sequential numbers automatically when initializers are omitted:
|
12 |
|
13 | ```ts
|
14 | enum Status {
|
15 | Open, // infer 0
|
16 | Closed, // infer 1
|
17 | }
|
18 | ```
|
19 |
|
20 | If a new member is added to the top of `Status`, both `Open` and `Closed` would have its values altered:
|
21 |
|
22 | ```ts
|
23 | enum Status {
|
24 | Pending, // infer 0
|
25 | Open, // infer 1
|
26 | Closed, // infer 2
|
27 | }
|
28 | ```
|
29 |
|
30 | Examples of code for this rule:
|
31 |
|
32 |
|
33 |
|
34 | ### ❌ Incorrect
|
35 |
|
36 | ```ts
|
37 | enum Status {
|
38 | Open = 1,
|
39 | Close,
|
40 | }
|
41 |
|
42 | enum Direction {
|
43 | Up,
|
44 | Down,
|
45 | }
|
46 |
|
47 | enum Color {
|
48 | Red,
|
49 | Green = 'Green'
|
50 | Blue = 'Blue',
|
51 | }
|
52 | ```
|
53 |
|
54 | ### ✅ Correct
|
55 |
|
56 | ```ts
|
57 | enum Status {
|
58 | Open = 'Open',
|
59 | Close = 'Close',
|
60 | }
|
61 |
|
62 | enum Direction {
|
63 | Up = 1,
|
64 | Down = 2,
|
65 | }
|
66 |
|
67 | enum Color {
|
68 | Red = 'Red',
|
69 | Green = 'Green',
|
70 | Blue = 'Blue',
|
71 | }
|
72 | ```
|
73 |
|
74 | ## Options
|
75 |
|
76 | ```jsonc
|
77 | // .eslintrc.json
|
78 | {
|
79 | "rules": {
|
80 | "@typescript-eslint/prefer-enum-initializers": "warn"
|
81 | }
|
82 | }
|
83 | ```
|
84 |
|
85 | This rule is not configurable.
|
86 |
|
87 | ## When Not To Use It
|
88 |
|
89 | If you don't care about `enum`s having implicit values you can safely disable this rule.
|
90 |
|
91 | ## Attributes
|
92 |
|
93 | - Configs:
|
94 | - [ ] ✅ Recommended
|
95 | - [ ] 🔒 Strict
|
96 | - [ ] 🔧 Fixable
|
97 | - [ ] 💭 Requires type information
|