Skip to content

Latest commit

 

History

History
97 lines (72 loc) · 1.49 KB

prefer-enum-initializers.md

File metadata and controls

97 lines (72 loc) · 1.49 KB

prefer-enum-initializers

Prefer initializing each enums member value.

This rule recommends having each enums member value explicitly initialized.

enums are a practical way to organize semantically related constant values. However, by implicitly defining values, enums can lead to unexpected bugs if it's modified without paying attention to the order of its items.

Rule Details

enums infers sequential numbers automatically when initializers are omitted:

enum Status {
  Open, // infer 0
  Closed, // infer 1
}

If a new member is added to the top of Status, both Open and Closed would have its values altered:

enum Status {
  Pending, // infer 0
  Open, // infer 1
  Closed, // infer 2
}

Examples of code for this rule:

❌ Incorrect

enum Status {
  Open = 1,
  Close,
}

enum Direction {
  Up,
  Down,
}

enum Color {
  Red,
  Green = 'Green'
  Blue = 'Blue',
}

✅ Correct

enum Status {
  Open = 'Open',
  Close = 'Close',
}

enum Direction {
  Up = 1,
  Down = 2,
}

enum Color {
  Red = 'Red',
  Green = 'Green',
  Blue = 'Blue',
}

Options

// .eslintrc.json
{
  "rules": {
    "@typescript-eslint/prefer-enum-initializers": "warn"
  }
}

This rule is not configurable.

When Not To Use It

If you don't care about enums having implicit values you can safely disable this rule.

Attributes

  • Configs:
    • ✅ Recommended
    • 🔒 Strict
  • 🔧 Fixable
  • 💭 Requires type information