Skip to main content

no-mixed-enums

Disallow enums from having both number and string members.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

💭

该规则需要 类型信息 才能运行。


TypeScript 枚举可以为其成员分配数字或字符串值。 大多数枚举包含所有数字或所有字符串,但理论上你可以在同一枚举中混合搭配。 混合枚举成员类型通常被认为是令人困惑且不好的做法。

英:TypeScript enums are allowed to assign numeric or string values to their members. Most enums contain either all numbers or all strings, but in theory you can mix-and-match within the same enum. Mixing enum member types is generally considered confusing and a bad practice.

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

示例

enum Status {
Unknown,
Closed = 1,
Open = 'open',
}
Open in Playground

混合枚举成员值的迭代陷阱

枚举值可以使用 Object.entries/Object.keys/Object.values 进行迭代。

英:Enum values may be iterated over using Object.entries/Object.keys/Object.values.

如果所有枚举成员都是字符串,则项目数将与枚举成员数匹配:

英:If all enum members are strings, the number of items will match the number of enum members:

enum Status {
Closed = 'closed',
Open = 'open',
}

// ['closed', 'open']
Object.values(Status);

但是如果枚举包含用数字初始化的成员 - 包括隐式初始化的数字— 然后对该枚举的迭代也将包括这些数字:

英:But if the enum contains members that are initialized with numbers -including implicitly initialized numbers— then iteration over that enum will include those numbers as well:

enum Status {
Unknown,
Closed = 1,
Open = 'open',
}

// ["Unknown", "Closed", 0, 1, "open"]
Object.values(Status);

何时不使用它

如果你不介意混合枚举成员值的混乱并且不迭代枚举,则可以安全地禁用此规则。

英:If you don't mind the confusion of mixed enum member values and don't iterate over enums, you can safely disable this rule.

选项

该规则不可配置。

资源