-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): [no-mixed-enums] add rule #6102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(eslint-plugin): [no-mixed-enums] add rule #6102
Conversation
Thanks for the PR, @JoshuaKGoldberg! typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community. The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately. Thanks again! 🙏 Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently on https://opencollective.com/typescript-eslint. |
✅ Deploy Preview for typescript-eslint ready!
To edit notification comments on pull requests, go to your Netlify site settings. |
Codecov Report
Additional details and impacted files@@ Coverage Diff @@
## main #6102 +/- ##
==========================================
- Coverage 91.52% 90.66% -0.87%
==========================================
Files 371 374 +3
Lines 12651 12823 +172
Branches 3717 3777 +60
==========================================
+ Hits 11579 11626 +47
- Misses 754 853 +99
- Partials 318 344 +26
Flags with carried forward coverage won't be shown. Click here to find out more.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
because enum members can sometimes have dynamically computed values
Note that number enum members are the only ones that are allow to have "complex" computed values:
declare function str(): string;
declare function num(): number;
declare const StRiNgCoNsTrUcToR: { new(): string };
declare const NuMbErCoNsTrUcToR: { new(): number };
enum Foo {
A = str(), // invalid
B = `${'a'}`, // invalid
C = str.name, // invalid
D = 'a' + 'b', // valid
E = new String(''), // invalid
F = new StRiNgCoNsTrUcToR(), // invalid
M = num(), // valid
N = Number.EPSILON, // valid
O = 1 + 1, // valid
P = new Number(1), // invalid
Q = new NuMbErCoNsTrUcToR(), // valid because it's dumb
}
This means we don't actually need the typechecker here.
We can simply follow the following logic:
- if no initialiser, number
- if initialiser
- if string literal or template literal, string
- if number literal, number
- if binary expression,
- if all operands are string literals or template literals, string
- else number
- if member expression, use type information to get the type
- else number
There is just one single caveat to this that I can see - enums built from enums:
enum Foo {
A = 1,
B = 'a',
}
enum Bar {
A = Foo.A,
B = Foo.B,
}
This is valid TS and creates a mixed enum. But IDK if we really care for this case? Could be a documented edge case that we wait for people to comment on? IDK.
TS even optimises `Bar` at transpile time so that it directly uses the literal values...!
var Foo;
(function (Foo) {
Foo[Foo["A"] = 1] = "A";
Foo["B"] = "a";
})(Foo || (Foo = {}));
var Bar;
(function (Bar) {
Bar[Bar["A"] = 1] = "A";
Bar["B"] = "a";
})(Bar || (Bar = {}));
Looking more, here is another case of valid TS that is dumb, declaration merging: enum Foo {
A = 1,
B = 1,
}
enum Foo {
C = 'c',
D = 'd',
} This will also create a mixed enum. This is much more difficult to handle without types though. I doubt your current code even handles it! Again, I'd be happy to just document and ignore this case cos this is so so so rare and is really dumb code. |
Oh, I've definitely seen this before. 😬 Thinking I'll try to handle it... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
okay - doing some research on the declaration merging case - I think you can only merge enums in the following cases:
- if both declarations are in the same file:
enum Foo { A = 1 } enum Foo { B = 2 } Foo.A; Foo.B;
- ambiently via module augmentation
import {AST_NODE_TYPES} from '@typescript-eslint/types'; declare module '@typescript-eslint/types' { enum AST_NODE_TYPES { WUT = 'WUT', } }
- via namespace declaration merging
namespace Test { export enum Bar { A = 1 } } namespace Test { export enum Bar { B = 2 } } Test.Bar.A; Test.Bar.B;
With that in mind - we can probably rework this rule to be faster.
WDYT of the following logic:
TSEnumDeclaration(node) {
let members = node.members;
if (
isWithinTSModuleDecl(node) ||
enumNameHasTwoDeclarationsInScope(node)
) {
members = members.concat(getMergedMembers(node));
}
let desiredType: 'string' | 'number';
for (const member of members) {
const currentType: 'string' | 'number' =
getTypeFromAST(member) ?? getTypeFromTypeInfo(member);
desiredType ??= currentType;
if (desiredType !== currentType) {
report(member);
}
}
}
This way we stay fast for cases that we know should be fast (which should be the vast, vast majority of code and cases), and we only dip into the slow type info for the weird edge-cases.
WDYT?
Aha you're totally right - thanks for pressing on this! +1. Will do. It's a pity we can't quite make it to untyped - but yes I do like that this is non-type-checked mostly. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
overall LGTM!
Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.52.0` -> `5.53.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2feslint-plugin/5.52.0/5.53.0) | | [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.52.0` -> `5.53.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2fparser/5.52.0/5.53.0) | --- ### Release Notes <details> <summary>typescript-eslint/typescript-eslint (@​typescript-eslint/eslint-plugin)</summary> ### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#​5530-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5520v5530-2023-02-20) [Compare Source](typescript-eslint/typescript-eslint@v5.52.0...v5.53.0) ##### Features - **eslint-plugin:** \[consistent-generic-constructors] handle default parameters ([#​6484](typescript-eslint/typescript-eslint#6484)) ([e8cebce](typescript-eslint/typescript-eslint@e8cebce)) - **eslint-plugin:** \[no-mixed-enums] add rule ([#​6102](typescript-eslint/typescript-eslint#6102)) ([16144d1](typescript-eslint/typescript-eslint@16144d1)) </details> <details> <summary>typescript-eslint/typescript-eslint (@​typescript-eslint/parser)</summary> ### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/parser/CHANGELOG.md#​5530-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5520v5530-2023-02-20) [Compare Source](typescript-eslint/typescript-eslint@v5.52.0...v5.53.0) **Note:** Version bump only for package [@​typescript-eslint/parser](https://github.com/typescript-eslint/parser) </details> --- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNC4xNDYuMSIsInVwZGF0ZWRJblZlciI6IjM0LjE0OS4wIn0=--> Co-authored-by: cabr2-bot <cabr2.help@gmail.com> Reviewed-on: https://codeberg.org/Calciumdibromid/CaBr2/pulls/1791 Reviewed-by: Epsilon_02 <epsilon_02@noreply.codeberg.org> Co-authored-by: Calciumdibromid Bot <cabr2_bot@noreply.codeberg.org> Co-committed-by: Calciumdibromid Bot <cabr2_bot@noreply.codeberg.org>
PR Checklist
Overview
Adds a
no-mixed-enums
rule that flags the first member of an enum that mismatches its type compared to previous members. Uses the type checker for this because enum members can sometimes have dynamically computed values:Doesn't ban specifically numeric and/or string member values. Both are extremely common patterns and I don't think there's enough user demand to justify that.
Borrows some documentation from #3891. Thanks 😄
Co-authored-by: @brianconnoly