Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.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 ourterms of service andprivacy 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
Uh oh!
There was an error while loading.Please reload this page.
Conversation
nx-cloudbot commentedNov 27, 2022 • edited
Loading Uh oh!
There was an error while loading.Please reload this page.
edited
Uh oh!
There was an error while loading.Please reload this page.
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 onhttps://opencollective.com/typescript-eslint. |
netlifybot commentedNov 27, 2022 • edited
Loading Uh oh!
There was an error while loading.Please reload this page.
edited
Uh oh!
There was an error while loading.Please reload this page.
✅ Deploy Preview fortypescript-eslint ready!
To edit notification comments on pull requests, go to yourNetlify site settings. |
codecovbot commentedNov 27, 2022 • edited
Loading Uh oh!
There was an error while loading.Please reload this page.
edited
Uh oh!
There was an error while loading.Please reload this page.
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.
|
bradzacher left a comment• edited
Loading Uh oh!
There was an error while loading.Please reload this page.
edited
Uh oh!
There was an error while loading.Please reload this page.
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:
declarefunctionstr():string;declarefunctionnum():number;declareconstStRiNgCoNsTrUcToR:{new():string};declareconstNuMbErCoNsTrUcToR:{new():number};enumFoo{A=str(),// invalidB=`${'a'}`,// invalidC=str.name,// invalidD='a'+'b',// validE=newString(''),// invalidF=newStRiNgCoNsTrUcToR(),// invalidM=num(),// validN=Number.EPSILON,// validO=1+1,// validP=newNumber(1),// invalidQ=newNuMbErCoNsTrUcToR(),// 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:
enumFoo{A=1,B='a',}enumBar{A=Foo.A,B=Foo.B,}
This is valid TS and creates a mixed enum. But IDK if wereally 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...!
varFoo;(function(Foo){Foo[Foo["A"]=1]="A";Foo["B"]="a";})(Foo||(Foo={}));varBar;(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: enumFoo{A=1,B=1,}enumFoo{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:
enumFoo{A=1}enumFoo{B=2}Foo.A;Foo.B;
- ambiently via module augmentation
import{AST_NODE_TYPES}from'@typescript-eslint/types';declare module'@typescript-eslint/types'{enumAST_NODE_TYPES{WUT='WUT',}}
- via namespace declaration merging
namespaceTest{exportenumBar{A=1}}namespaceTest{exportenumBar{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){letmembers=node.members;if(isWithinTSModuleDecl(node)||enumNameHasTwoDeclarationsInScope(node)){members=members.concat(getMergedMembers(node));}letdesiredType:'string'|'number';for(constmemberofmembers){constcurrentType:'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. |
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
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!
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
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/1791Reviewed-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>
Uh oh!
There was an error while loading.Please reload this page.
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