Skip to content

Latest commit

 

History

History
106 lines (80 loc) · 2.64 KB

prefer-literal-enum-member.md

File metadata and controls

106 lines (80 loc) · 2.64 KB

prefer-literal-enum-member

Require that all enum members be literal values to prevent unintended enum member name shadow issues.

TypeScript allows the value of an enum member to be many different kinds of valid JavaScript expressions. However, because enums create their own scope whereby each enum member becomes a variable in that scope, unexpected values could be used at runtime. Example:

const imOutside = 2;
const b = 2;
enum Foo {
  outer = imOutside,
  a = 1,
  b = a,
  c = b,
  // does c == Foo.b == Foo.c == 1?
  // or does c == b == 2?
}

The answer is that Foo.c will be 1 at runtime. The playground illustrates this quite nicely.

Rule Details

This rule is meant to prevent unexpected results in code by requiring the use of literal values as enum members to prevent unexpected runtime behavior. Template literals, arrays, objects, constructors, and all other expression types can end up using a variable from its scope or the parent scope, which can result in the same unexpected behavior at runtime.

Options

  • allowBitwiseExpressions set to true will allow you to use bitwise expressions in enum initializer (Default: false).

Examples of code for this rule:

❌ Incorrect

const str = 'Test';
enum Invalid {
  A = str, // Variable assignment
  B = {}, // Object assignment
  C = `A template literal string`, // Template literal
  D = new Set(1, 2, 3), // Constructor in assignment
  E = 2 + 2, // Expression assignment
}

✅ Correct

enum Valid {
  A,
  B = 'TestStr', // A regular string
  C = 4, // A number
  D = null,
  E = /some_regex/,
}

allowBitwiseExpressions

Examples of code for the { "allowBitwiseExpressions": true } option:

❌ Incorrect

const x = 1;
enum Foo {
  A = x << 0,
  B = x >> 0,
  C = x >>> 0,
  D = x | 0,
  E = x & 0,
  F = x ^ 0,
  G = ~x,
}

✅ Correct

enum Foo {
  A = 1 << 0,
  B = 1 >> 0,
  C = 1 >>> 0,
  D = 1 | 0,
  E = 1 & 0,
  F = 1 ^ 0,
  G = ~1,
}

When Not To Use It

If you want use anything other than simple literals as an enum value.

Attributes

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