prefer-enum-initializers
Require each enum member value to be explicitly initialized.
💡
此规则报告的一些问题可以通过编辑器 建议 手动修复。
TypeScript enum
是一种组织语义相关常量值的实用方法。没有明确值的 enum
成员默认被赋予连续递增的数字。
¥TypeScript enum
s are a practical way to organize semantically related constant values.
Members of enum
s that don't have explicit values are by default given sequentially increasing numbers.
在 enum
成员的值很重要的项目中,如果 enum
随着时间的推移而被修改,则允许枚举的隐式值可能会导致错误。
¥In projects where the value of enum
members are important, allowing implicit values for enums can cause bugs if enum
s are modified over time.
此规则报告在已使用 ES 模 块的文件中不执行任何操作的 enum
。
¥This rule recommends having each enum
member value explicitly initialized.
- Flat Config
- Legacy Config
eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-enum-initializers": "error"
}
});
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-enum-initializers": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
enum Status {
Open = 1,
Close,
}
enum Direction {
Up,
Down,
}
enum Color {
Red,
Green = 'Green',
Blue = 'Blue',
}
Open in Playgroundenum Status {
Open = 'Open',
Close = 'Close',
}
enum Direction {
Up = 1,
Down = 2,
}
enum Color {
Red = 'Red',
Green = 'Green',
Blue = 'Blue',
}
Open in Playground