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-magic-numbers] ignoreTypeIndexes option#4789

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

Conversation

davecardwell
Copy link
Contributor

PR Checklist

Overview

Add a newignoreTypeIndexes option to theno-magic-numbers rule to allow magic numbers in type index access (eg.Foo[4]).

Itsounds like@timdeschryver and I have both worked on this, so if this PR has major structural issues I’m happy to close this one in favor of his, or otherwise am happy to make any adjustments to see this one over the line.

Add a new `ignoreTypeIndexes` option to the `no-magic-numbers` rule toallow magic numbers in type index access (eg. `Foo[4]`).
@nx-cloud
Copy link

nx-cloudbot commentedApr 5, 2022
edited
Loading

☁️ Nx Cloud Report

CI is running/has finished running commands for commit88bd7e4. 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 43 targets

Sent with 💌 fromNxCloud.

@typescript-eslint
Copy link
Contributor

Thanks for the PR,@davecardwell!

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. As a thank you, your profile/company logo will be added to our main README which receives thousands of unique visitorsper day.

@netlify
Copy link

netlifybot commentedApr 5, 2022
edited
Loading

Deploy Preview fortypescript-eslint ready!

NameLink
🔨 Latest commit88bd7e4
🔍 Latest deploy loghttps://app.netlify.com/sites/typescript-eslint/deploys/6259923ea702430008ef9947
😎 Deploy Previewhttps://deploy-preview-4789--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.

@codecov
Copy link

codecovbot commentedApr 5, 2022
edited
Loading

Codecov Report

Merging#4789 (af1ddb7) intomain (18a81cb) willincrease coverage by0.28%.
The diff coverage is83.33%.

❗ Current headaf1ddb7 differs from pull request most recent head88bd7e4. Consider uploading reports for the commit88bd7e4 to get more accurate results

@@            Coverage Diff             @@##             main    #4789      +/-   ##==========================================+ Coverage   93.96%   94.24%   +0.28%==========================================  Files         172      151      -21       Lines        9818     8230    -1588       Branches     3105     2676     -429     ==========================================- Hits         9225     7756    -1469+ Misses        353      262      -91+ Partials      240      212      -28
FlagCoverage Δ
unittest94.24% <83.33%> (+0.28%)⬆️

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

Impacted FilesCoverage Δ
...ckages/eslint-plugin/src/rules/no-magic-numbers.ts80.64% <83.33%> (-2.05%)⬇️
packages/typescript-estree/src/simple-traverse.ts
...pt-estree/src/create-program/createWatchProgram.ts
...plugin-internal/src/rules/prefer-ast-types-enum.ts
...t-estree/src/create-program/useProvidedPrograms.ts
...gin-internal/src/rules/no-poorly-typed-ts-props.ts
...ript-estree/src/create-program/createSourceFile.ts
...escript-estree/src/semantic-or-syntactic-errors.ts
...-estree/src/create-program/createDefaultProgram.ts
packages/typescript-estree/src/version-check.ts
... and12 more

(typeof node.value === 'number' || typeof node.value === 'bigint') &&
isAncestorTSIndexedAccessType(node)
) {
return;
Copy link
Contributor

Choose a reason for hiding this comment

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

FWIW, this looks good to me.
The only difference with my implementation is that I reported invalid nodes in this statement, similar to "Check if the node is a readonly class property". This way, we can return early which should be faster?

Also, good catch for the union types - this was something that I overlooked.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@timdeschryver Thanks! I refactored things a little ind1e65be so if any of the four ignorable TypeScript rules are triggered it will report early. Is that better?

Copy link
Contributor

@timdeschryvertimdeschryverApr 6, 2022
edited
Loading

Choose a reason for hiding this comment

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

Yea, this should work.
If we go into more details I would remove theelse if (isAllowed === false) statement to remove the indentation, and perhaps move theisAllowed logic into its own method.

Keep in mind that I'm not a member of typescript-eslint 😅

JoshuaKGoldberg reacted with thumbs up emojiJoshuaKGoldberg reacted with heart emoji
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@timdeschryver Realized I never responded to this, sorry - and thank you for the feedback.

remove theelse if (isAllowed === false) statement

I don’t think I can remove theisAllowed === false case because it’s possible forisAllowed to beundefined, so I intend to explicitly check if it istrue orfalse in thatif/else if block. If it is neither it will fall back to the base rule.

Perhaps I should move the finalrules.Literal(node); line of the function into anelse block to make that more explicit?

move theisAllowed logic into its own method

Looking at a few other rule definitions at random it does seem like they keep the core rule logic in thecreate function, which makes sense to me. I’m not sure movingisAllowed into its own function would improve readability, and feels like it would simply cause people to have to jump to look elsewhere for what is essentially the meat of the rule.

Feel free to push back if you (or@JoshuaKGoldberg?) disagree though, and I will happily take another look.

Copy link
Contributor

Choose a reason for hiding this comment

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

No problem@davecardwell !
Thanks for the elaboration, that does make sense.

Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Looks great so far, thanks! Just requesting some more unit tests.

type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
```

Choose a reason for hiding this comment

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

Heh, it's a pity this docs page doesn't use the newer tabbed format others do. No need to change in this PR though; I'm going to try to make docs a bit more automated soon.

{
code: "type Foo = Bar['baz'];",
options: [{ ignoreTypeIndexes: false }],
},

Choose a reason for hiding this comment

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

A few edge cases we'll also want to test for:

typeFoo=Bar[1&number];
typeOther={[0]:3;}typeFoo={[KinkeyofOther]: `${K&number}`;};
typeFoo={[Kin0|1|2]:0;};
typeOthers=[['a'],['b']];typeFoo={[KinkeyofOthers[0]]:Others[K];};

timdeschryver reacted with thumbs up emoji
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@JoshuaKGoldberg couple of quick questions on those:

typeFoo=Bar[1&number];

Sure, I check for union types so intersection should be covered too! Thanks.

typeOther={[0]:3;}typeFoo={[KinkeyofOther]: `${K&number}`;};

Since the0 is aTSPropertySignature, not aTSIndexedAccessType, would you still want it to be covered by this newignoreTypeIndexes config? Seems like that should be a separate config?

Also, the3 thereshould be an error, right? So perhapsstring or some other non-numeric literal would be more appropriate for this test case?

typeFoo={[Kin0|1|2]:0;};

As above,TSPropertySignature.

typeOthers=[['a'],['b']];typeFoo={[KinkeyofOthers[0]]:Others[K];};

I’ll add a test to ensure theOthers[0] part is covered.

Choose a reason for hiding this comment

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

Great questions!

check for union types so intersection should be covered too

Bar[1 & number] is a bit different syntax from${K & number}. I think it'd be good to have an explicit test for both. The code right now might not differentiate, but it's ripe for future refactors to miss it.

Since the 0 is aTSPropertySignature, not aTSIndexedAccessType, would you still want it to be covered by this newignoreTypeIndexes config?

I'm not requesting changes to logic, just that it be covered. Agreed that they're different things -- the tests should validate thatignoreTypeIndexesdoesn't remove the complaint on it.

Also, the 3 thereshould be an error, right?

Yes. That's already covered though; I'm really more interested in theTSPropertySignature.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@JoshuaKGoldberg Thank you for clarifying. Inaf1ddb7 I added support for intersection types, nesting of union/intersection types, and the additional invalid test cases you suggested.

JoshuaKGoldberg reacted with rocket emoji
@bradzacherbradzacher added enhancement: plugin rule optionNew rule option for an existing eslint-plugin rule awaiting responseIssues waiting for a reply from the OP or another party labelsApr 9, 2022
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Super, thanks for working on this@davecardwell! 🙌

davecardwell reacted with thumbs up emoji
@JoshuaKGoldbergJoshuaKGoldbergenabled auto-merge (squash)April 15, 2022 15:41
@JoshuaKGoldbergJoshuaKGoldberg merged commit5e79451 intotypescript-eslint:mainApr 15, 2022
@davecardwelldavecardwell deleted the feat-no_magic_numbers-ignore_array_indexes branchApril 15, 2022 15:53
crapStone pushed a commit to Calciumdibromid/CaBr2 that referenced this pull requestApr 25, 2022
This PR contains the following updates:| Package | Type | Update | Change ||---|---|---|---|| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.19.0` -> `5.20.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2feslint-plugin/5.19.0/5.20.0) || [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.19.0` -> `5.20.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2fparser/5.19.0/5.20.0) |---### Release Notes<details><summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/eslint-plugin)</summary>### [`v5.20.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#&#8203;5200-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5190v5200-2022-04-18)[Compare Source](typescript-eslint/typescript-eslint@v5.19.0...v5.20.0)##### Features-   **eslint-plugin:** \[no-magic-numbers] ignoreTypeIndexes option ([#&#8203;4789](typescript-eslint/typescript-eslint#4789)) ([5e79451](typescript-eslint/typescript-eslint@5e79451))</details><details><summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/parser)</summary>### [`v5.20.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/parser/CHANGELOG.md#&#8203;5200-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5190v5200-2022-04-18)[Compare Source](typescript-eslint/typescript-eslint@v5.19.0...v5.20.0)**Note:** Version bump only for package [@&#8203;typescript-eslint/parser](https://github.com/typescript-eslint/parser)</details>---### Configuration📅 **Schedule**: 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, click this checkbox.---This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).Co-authored-by: cabr2-bot <cabr2.help@gmail.com>Reviewed-on:https://codeberg.org/Calciumdibromid/CaBr2/pulls/1312Reviewed-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 collaboratorsMay 23, 2022
Sign up for freeto subscribe to this conversation on GitHub. Already have an account?Sign in.
Reviewers

@timdeschryvertimdeschryvertimdeschryver left review comments

@JoshuaKGoldbergJoshuaKGoldbergJoshuaKGoldberg approved these changes

Assignees
No one assigned
Labels
awaiting responseIssues waiting for a reply from the OP or another partyenhancement: plugin rule optionNew rule option for an existing eslint-plugin rule
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

[no-magic-numbers] False positive with array/tuple type index access
4 participants
@davecardwell@JoshuaKGoldberg@timdeschryver@bradzacher

[8]ページ先頭

©2009-2025 Movatter.jp