prefer-literal-enum-member
要求所有枚舉成員為文字值。
🔒
延伸 "plugin:@typescript-eslint/strict"
在 ESLint 配置中 啟用這項規則。
TypeScript 允許枚舉成員的值為許多不同類型的有效 JavaScript 表達式。但是,由於枚舉會建立它們自己的範圍,而每個枚舉成員在該範圍中會變為一個變數,因此開發人員經常對於產生的值感到驚訝。例如
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?
}
答案是
Foo.c
在執行階段會是1
[TypeScript 操場]
因此,透過要求使用文字值作為列舉成員,通常能較好地防止程式碼產生預期之外的結果。當列舉成員獲賦與非文字值時,此規則會回報。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-literal-enum-member": "error"
}
};
在 Playground 中試試這個規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
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
}
在 Playground 中開啟enum Valid {
A,
B = 'TestStr', // A regular string
C = 4, // A number
D = null,
E = /some_regex/,
}
在 Playground 中開啟選項
此規則接受下列選項
type Options = [
{
allowBitwiseExpressions?: boolean;
},
];
const defaultOptions: Options = [{ allowBitwiseExpressions: false }];
allowBitwiseExpressions
設為 true
時,允許你在列舉初始化程式中使用位元運算式(預設值:false
)。
{ "allowBitwiseExpressions": true }
選項的程式碼範例
- ❌ 錯誤
- ✅ 正確
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,
}
在 Playground 中開啟enum Foo {
A = 1 << 0,
B = 1 >> 0,
C = 1 >>> 0,
D = 1 | 0,
E = 1 & 0,
F = 1 ^ 0,
G = ~1,
}
在 Playground 中開啟何時不使用
如果你想使用除了簡單文字值以外的其他任何內容作為列舉值,那麼這個規則可能不適合你。