Skip to main content

prefer-enum-initializers

Require each enum member value to be explicitly initialized.

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。


TypeScript enum 是组织语义相关常量值的实用方法。 默认情况下,没有显式值的 enum 成员按顺序递增。

英:TypeScript enums are a practical way to organize semantically related constant values. Members of enums 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 enums are modified over time.

此规则建议显式初始化每个 enum 成员值。

英:This rule recommends having each enum member value explicitly initialized.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-enum-initializers": "error"
}
};
在线运行试试这个规则 ↗

示例

enum Status {
Open = 1,
Close,
}

enum Direction {
Up,
Down,
}

enum Color {
Red,
Green = 'Green'
Blue = 'Blue',
}
Open in Playground

何时不使用它

如果你不关心 enum 具有隐式值,你可以安全地禁用此规则。

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

选项

该规则不可配置。

资源