no-mixed-enums
Disallow enums from having both number and string members.
Extending "plugin:@typescript-eslint/strict-type-checked"
in an ESLint configuration enables this rule.
This rule requires type information to run.
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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-mixed-enums": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-mixed-enums": "error"
}
};
Try this rule in the playground β
Examplesβ
- β Incorrect
- β Correct (Explicit Numbers)
- β Correct (Implicit Numbers)
- β Correct (Strings)
enum Status {
Unknown,
Closed = 1,
Open = 'open',
}
Open in Playgroundenum Status {
Unknown = 0,
Closed = 1,
Open = 2,
}
Open in Playgroundenum Status {
Unknown,
Closed,
Open,
}
Open in Playgroundenum Status {
Unknown = 'unknown',
Closed = 'closed',
Open = 'open',
}
Open in PlaygroundIteration Pitfalls of Mixed Enum Member 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);
Optionsβ
This rule is not configurable.
When Not To Use Itβ
If you don't mind the confusion of mixed enum member values and don't iterate over enums, you can safely disable this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.