Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Merged

Conversation

JoshuaKGoldberg
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg commentedNov 27, 2022
edited
Loading

PR Checklist

Overview

Adds ano-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:

enumAnnoying{Gotcha=Math.random()}

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

omril1, brianconnoly, and uhyo reacted with rocket emoji
@nx-cloud
Copy link

nx-cloudbot commentedNov 27, 2022
edited
Loading

☁️ Nx Cloud Report

CI is running/has finished running commands for commit1de4847. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this branch


✅ Successfully ran 47 targets

Sent with 💌 fromNxCloud.

@typescript-eslint
Copy link
Contributor

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.

@netlify
Copy link

netlifybot commentedNov 27, 2022
edited
Loading

Deploy Preview fortypescript-eslint ready!

NameLink
🔨 Latest commit1de4847
🔍 Latest deploy loghttps://app.netlify.com/sites/typescript-eslint/deploys/63ee7f8c2cb5c300080afa22
😎 Deploy Previewhttps://deploy-preview-6102--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to yourNetlify site settings.

@JoshuaKGoldbergJoshuaKGoldberg marked this pull request as ready for reviewNovember 27, 2022 02:41
@codecov
Copy link

codecovbot commentedNov 27, 2022
edited
Loading

Codecov Report

Merging#6102 (1de4847) intomain (f330e06) willdecrease coverage by0.87%.
The diff coverage is94.44%.

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
FlagCoverage Δ
unittest90.66% <94.44%> (-0.87%)⬇️

Flags with carried forward coverage won't be shown.Click here to find out more.

Impacted FilesCoverage Δ
packages/eslint-plugin/src/rules/no-mixed-enums.ts94.44% <94.44%> (ø)
packages/typescript-estree/src/convert-comments.ts57.14% <0.00%> (-42.86%)⬇️
packages/typescript-estree/src/convert.ts84.89% <0.00%> (-12.25%)⬇️
packages/typescript-estree/src/node-utils.ts83.51% <0.00%> (-7.45%)⬇️
...escript-estree/src/semantic-or-syntactic-errors.ts80.00% <0.00%> (-6.67%)⬇️
...pt-estree/src/parseSettings/createParseSettings.ts91.30% <0.00%> (-6.20%)⬇️
...ipt-estree/src/parseSettings/resolveProjectList.ts91.11% <0.00%> (-4.45%)⬇️
...ckages/eslint-plugin/src/util/getESLintCoreRule.ts75.00% <0.00%> (ø)
...nt-plugin/src/rules/no-import-type-side-effects.ts100.00% <0.00%> (ø)
...-estree/src/parseSettings/getProjectConfigFiles.ts100.00% <0.00%> (ø)
... and6 more

@bradzacherbradzacher added enhancement: plugin rule optionNew rule option for an existing eslint-plugin rule enhancement: new plugin ruleNew rule request for eslint-plugin and removed enhancement: plugin rule optionNew rule option for an existing eslint-plugin rule labelsJan 30, 2023
Copy link
Member

@bradzacherbradzacher left a comment
edited
Loading

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}

play

This means we don't actually need the typechecker here.
We can simply follow the following logic:

  1. if no initialiser, number
  2. if initialiser
    1. if string literal or template literal, string
    2. if number literal, number
    3. if binary expression,
      1. if all operands are string literals or template literals, string
      2. else number
    4. if member expression, use type information to get the type
    5. 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={}));

@bradzacher
Copy link
Member

Looking more, here is another case of valid TS that is dumb, declaration merging:

enumFoo{A=1,B=1,}enumFoo{C='c',D='d',}

playground

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.

@bradzacherbradzacher added the awaiting responseIssues waiting for a reply from the OP or another party labelJan 30, 2023
@JoshuaKGoldberg
Copy link
MemberAuthor

enums built from enums

Oh, I've definitely seen this before. 😬 Thinking I'll try to handle it...

@JoshuaKGoldbergJoshuaKGoldberg removed the awaiting responseIssues waiting for a reply from the OP or another party labelFeb 5, 2023
Copy link
Member

@bradzacherbradzacher left a 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:

  1. if both declarations are in the same file:
    enumFoo{A=1}enumFoo{B=2}Foo.A;Foo.B;
  2. ambiently via module augmentation
    import{AST_NODE_TYPES}from'@typescript-eslint/types';declare module'@typescript-eslint/types'{enumAST_NODE_TYPES{WUT='WUT',}}
  3. via namespace declaration merging
    namespaceTest{exportenumBar{A=1}}namespaceTest{exportenumBar{B=2}}Test.Bar.A;Test.Bar.B;

playground

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?

@bradzacherbradzacher added the awaiting responseIssues waiting for a reply from the OP or another party labelFeb 10, 2023
@JoshuaKGoldberg
Copy link
MemberAuthor

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.

bradzacher reacted with thumbs up emoji

@JoshuaKGoldbergJoshuaKGoldberg marked this pull request as draftFebruary 11, 2023 13:28
@JoshuaKGoldbergJoshuaKGoldberg marked this pull request as ready for reviewFebruary 15, 2023 00:53
bradzacher
bradzacher previously approved these changesFeb 16, 2023
Copy link
Member

@bradzacherbradzacher left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

overall LGTM!

@bradzacherbradzacher removed the awaiting responseIssues waiting for a reply from the OP or another party labelFeb 16, 2023
Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
@JoshuaKGoldbergJoshuaKGoldberg merged commit16144d1 intotypescript-eslint:mainFeb 16, 2023
crapStone pushed a commit to Calciumdibromid/CaBr2 that referenced this pull requestFeb 22, 2023
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 (@&#8203;typescript-eslint/eslint-plugin)</summary>### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#&#8203;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 ([#&#8203;6484](typescript-eslint/typescript-eslint#6484)) ([e8cebce](typescript-eslint/typescript-eslint@e8cebce))-   **eslint-plugin:** \[no-mixed-enums] add rule ([#&#8203;6102](typescript-eslint/typescript-eslint#6102)) ([16144d1](typescript-eslint/typescript-eslint@16144d1))</details><details><summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/parser)</summary>### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/parser/CHANGELOG.md#&#8203;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 [@&#8203;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>
@github-actionsgithub-actionsbot locked asresolvedand limited conversation to collaboratorsFeb 24, 2023
@JoshuaKGoldbergJoshuaKGoldberg deleted the no-mixed-enums branchFebruary 3, 2024 16:51
Sign up for freeto subscribe to this conversation on GitHub. Already have an account?Sign in.
Reviewers

@bradzacherbradzacherbradzacher left review comments

@Josh-CenaJosh-CenaAwaiting requested review from Josh-Cena

Assignees
No one assigned
Labels
enhancement: new plugin ruleNew rule request for eslint-plugin
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

Rule proposal: disallow mixed string/numeric enums
2 participants
@JoshuaKGoldberg@bradzacher

[8]ページ先頭

©2009-2025 Movatter.jp