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

fix(eslint-plugin): [no-for-in-array] report on any type which may be an array or array-like#10535

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

ronami
Copy link
Member

@ronamironami commentedDec 21, 2024
edited
Loading

PR Checklist

Overview

See#10535 (comment) for the updated contents of this PR.

This PR tackles#10534 and reports on cases such as:

declareconstmaybeArr:string[]|undefined;declareconstarr:string[];// fails correctlyfor(constiteminarr){}// should fail, same with `T[] | null`for(constiteminmaybeArr){}

@typescript-eslint
Copy link
Contributor

Thanks for the PR,@ronami!

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.

@nx-cloudNx Cloud
Copy link

nx-cloudbot commentedDec 21, 2024
edited
Loading

View yourCI Pipeline Execution ↗ for commit599ac75.

CommandStatusDurationResult
nx test eslint-plugin --coverage=false✅ Succeeded7m 27sView ↗
nx test eslint-plugin✅ Succeeded5m 46sView ↗
nx test typescript-eslint --coverage=false✅ Succeeded22sView ↗
nx test visitor-keys --coverage=false✅ Succeeded<1sView ↗
nx run types:build✅ Succeeded<1sView ↗
nx run-many --target=build --exclude website --...✅ Succeeded29sView ↗
nx test rule-schema-to-typescript-types --cover...✅ Succeeded<1sView ↗
nx test typescript-estree --coverage=false✅ Succeeded<1sView ↗
Additional runs (24)✅ Succeeded...View ↗

☁️Nx Cloud last updated this comment at2025-01-11 14:26:31 UTC

@netlifyNetlify
Copy link

netlifybot commentedDec 21, 2024
edited
Loading

Deploy Preview fortypescript-eslint ready!

NameLink
🔨 Latest commit599ac75
🔍 Latest deploy loghttps://app.netlify.com/sites/typescript-eslint/deploys/67827b1af77a0900086da4c5
😎 Deploy Previewhttps://deploy-preview-10535--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 94 (🟢 up 1 from production)
Accessibility: 100 (no change from production)
Best Practices: 92 (no change from production)
SEO: 98 (no change from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

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

@codecovCodecov
Copy link

codecovbot commentedDec 21, 2024
edited
Loading

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 86.95%. Comparing base(3ae4148) to head(599ac75).
Report is 52 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@##             main   #10535      +/-   ##==========================================+ Coverage   86.86%   86.95%   +0.09%==========================================  Files         445      446       +1       Lines       15455    15517      +62       Branches     4507     4519      +12     ==========================================+ Hits        13425    13493      +68+ Misses       1675     1669       -6  Partials      355      355
FlagCoverage Δ
unittest86.95% <100.00%> (+0.09%)⬆️

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

Files with missing linesCoverage Δ
...ackages/eslint-plugin/src/rules/no-for-in-array.ts100.00% <100.00%> (ø)

... and23 files with indirect coverage changes

@ronamironami marked this pull request as ready for reviewDecember 21, 2024 16:17
@@ -45,3 +45,20 @@ export default createRule({
};
},
});

function isTypeArrayTypeOrUnionOfArrayTypes(

Choose a reason for hiding this comment

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

(style) avoid having the identical name function but with different behavior compared to theisTypeArrayTypeOrUnionOfArrayTypes in utils?

ronami reacted with thumbs up emoji
Comment on lines 53 to 63
for (const t of tsutils.unionTypeParts(type)) {
if (tsutils.isTypeFlagSet(t, ts.TypeFlags.Undefined | ts.TypeFlags.Null)) {
continue;
}

if (!checker.isArrayType(t)) {
return false;
}
}

return true;

Choose a reason for hiding this comment

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

(optional) This fixes a sort-of bug where a purely nullish type is considered an array type... "sort-of", since TS reports an error for the cases where the rule would reach this bug.

Suggested change
for(consttoftsutils.unionTypeParts(type)){
if(tsutils.isTypeFlagSet(t,ts.TypeFlags.Undefined|ts.TypeFlags.Null)){
continue;
}
if(!checker.isArrayType(t)){
returnfalse;
}
}
returntrue;
constnonNullishParts=tsutils
.unionTypeParts(type)
.filter(
t=>
!tsutils.isTypeFlagSet(t,ts.TypeFlags.Undefined|ts.TypeFlags.Null),
);
return(
nonNullishParts.length>0&&
nonNullishParts.every(t=>checker.isArrayType(t))
);

ronami reacted with thumbs up emoji

Choose a reason for hiding this comment

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

(test case)

Playground

declareconstnullish:null|undefined;//@ts-expect-errorfor(constkinnullish){}

Copy link
Member

@kirkwaiblingerkirkwaiblinger left a comment

Choose a reason for hiding this comment

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

Requesting changes here just to account for conversation on the backing issue#10534 (comment)

ronami reacted with thumbs up emoji
@ronami
Copy link
MemberAuthor

ronami commentedDec 27, 2024
edited
Loading

I've updated the rule to report on anything that may be an array (along with some array-likes). Some notes:

Some of the changes above don't have a dedicated issue that's marked asopen-PRs, but they made sense as the changes are minimal and somewhat relate to the original issue this PR addresses. Please let me know if I should revert anything to make the PR match the original issue.

Remaining things that I think may benefit the rule (I'll consider opening issues for these):

  • No suggestion fixer, even though most of the time (or so I think) it's a mistake and should instead befor..of.

Thanks@kirkwaiblinger 👍

kirkwaiblinger reacted with heart emoji

@ronamironami changed the titlefix(eslint-plugin): [no-for-in-array] report on for-in usage with 'Array<T> | undefined'fix(eslint-plugin): [no-for-in-array] report on any type which may be an array or array-likeDec 27, 2024
Comment on lines 62 to 78
function isArray(checker: ts.TypeChecker, type: ts.Type): boolean {
return isTypeRecurser(
type,
t => checker.isArrayType(t) || checker.isTupleType(t),
);
}

function isTypeRecurser(
type: ts.Type,
predicate: (t: ts.Type) => boolean,
): boolean {
if (type.isUnionOrIntersection()) {
return type.types.some(t => isTypeRecurser(t, predicate));
}

return predicate(type);
}
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

I've used this part from#10551.

'IArguments',
'HTMLCollection',
'RegExpExecArray',
'NodeList',
Copy link
MemberAuthor

@ronamironamiDec 28, 2024
edited by kirkwaiblinger
Loading

Choose a reason for hiding this comment

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

I'm not an expert on array-likes, basing this onhttps://developer.mozilla.org/en-US/docs/Web/API/NodeList.

kirkwaiblinger reacted with thumbs up emoji
return isTypeRecurser(type, t =>
isBuiltinSymbolLike(program, t, [
'IArguments',
'HTMLCollection',
Copy link
MemberAuthor

@ronamironamiDec 28, 2024
edited by kirkwaiblinger
Loading

Choose a reason for hiding this comment

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

I'm not an expert on array-likes, basing this onhttps://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.

kirkwaiblinger reacted with thumbs up emoji
Comment on lines +1 to +6
{
"extends": "./tsconfig.json",
"compilerOptions": {
"lib": ["es2015", "es2017", "esnext", "dom"]
}
}
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Is there a better way to do this? Specificallydom is necessary for the two dom-array-likes.

Choose a reason for hiding this comment

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

Yep, this is good!

ronami reacted with thumbs up emoji
@kirkwaiblinger
Copy link
Member

Remaining things that I think may benefit the rule (I'll consider opening issues for these):

  • No suggestion fixer, even though most of the time (or so I think) it's a mistake and should instead befor..of.

For this, the complexity is that

for(constainx){console.log(a);}

can't be directly fixed to a for-of loop equivalent since the for of would iterate array values and not string keys. So we'd have to be vigilant about keys only used for indexing or something. Note thatprefer-for-of is in a similar area and may have design and logic for that that we could reuse. In any case punting to a separate issue is a good idea 👍

ronami reacted with thumbs up emoji

@@ -45,3 +42,32 @@ export default createRule({
};
},
});

function isArrayLike(program: ts.Program, type: ts.Type): boolean {
Copy link
Member

@kirkwaiblingerkirkwaiblingerJan 7, 2025
edited
Loading

Choose a reason for hiding this comment

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

I wonder how much hard-coding we can cut down on...
forRegExpExecArray (and Array subclasses in general I think)checker.isArrayLikeType(type) will take care of it.

The rest, though, require a bit more thinking. (With a bit of inspiration from some NVIDIA GPUs,) I was able to get all test cases passing with this approach:

import*astsfrom'typescript';import{createRule,getConstrainedTypeAtLocation,getParserServices,}from'../util';import{getForStatementHeadLoc}from'../util/getForStatementHeadLoc';exportdefaultcreateRule({name:'no-for-in-array',meta:{type:'problem',docs:{description:'Disallow iterating over an array with a for-in loop',recommended:'recommended',requiresTypeChecking:true,},messages:{forInViolation:'For-in loops over arrays skips holes, returns indices as strings, and may visit the prototype chain or other enumerable properties. Use a more robust iteration method such as for-of or array.forEach instead.',},schema:[],},defaultOptions:[],create(context){return{ForInStatement(node):void{constservices=getParserServices(context);consttype=getConstrainedTypeAtLocation(services,node.right);if(isArrayLike(services.program,type)){context.report({loc:getForStatementHeadLoc(context.sourceCode,node),messageId:'forInViolation',});}},};},});functionisArrayLike(program:ts.Program,type:ts.Type):boolean{returnisTypeRecurser(type,t=>{constchecker=program.getTypeChecker();consthasNumberyLength=(()=>{constlengthProperty=t.getProperty('length');if(lengthProperty!=null){constlengthType=checker.getTypeOfSymbol(lengthProperty);if(lengthType.flags&ts.TypeFlags.NumberLike){returntrue;}}returnfalse;})();consthasNumberyIndex=(()=>{constindexSignature=t.getNumberIndexType();returnindexSignature!=null;})();returnhasNumberyIndex&&hasNumberyLength;});}functionisTypeRecurser(type:ts.Type,predicate:(t:ts.Type)=>boolean,):boolean{if(type.isUnionOrIntersection()){returntype.types.some(t=>isTypeRecurser(t,predicate));}returnpredicate(type);}

But I haven't thought deeply whether this is a good idea. What do you think?

ronami reacted with thumbs up emojironami reacted with eyes emoji
Copy link
MemberAuthor

@ronamironamiJan 11, 2025
edited
Loading

Choose a reason for hiding this comment

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

Interesting approach, and it seems TypeScript doessome similar checks internally too. My intuition is to be careful with a check like that, in case it may flag false positives, but testing this on various cases, it seems to work nicely (though it is possible I've missed something). It does report on objects such as the following, which I think is intended (in addition to thearguments and several other array-likes):

declareconstobj:{[key:number]:number;length:1;};for(constainobj){//}

I agree that hard-coding specific array-likes isn't very optimal. In my opinion, we should either use the plain and saferchecker.isArrayLikeType() and avoid reporting array-likes that it doesn't detect or use this custom way to check array-likes. I think I'm +1 to using this over the plainchecker.isArrayLikeType() but still a bit hesitant in case it over-reports.

I've updated the PR to match this, thanks 👍

kirkwaiblinger reacted with thumbs up emoji
@kirkwaiblingerkirkwaiblinger added the awaiting responseIssues waiting for a reply from the OP or another party labelJan 7, 2025
@github-actionsgithub-actionsbot removed the awaiting responseIssues waiting for a reply from the OP or another party labelJan 11, 2025
Copy link
Member

@kirkwaiblingerkirkwaiblinger left a comment

Choose a reason for hiding this comment

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

I'm happy!

ronami reacted with heart emoji
@kirkwaiblingerkirkwaiblinger added the 1 approval>=1 team member has approved this PR; we're now leaving it open for more reviews before we merge labelJan 19, 2025
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg 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.

+1, this is sweet. 🍬

ronami reacted with heart emoji
@JoshuaKGoldbergJoshuaKGoldberg merged commit74f1c5a intotypescript-eslint:mainJan 19, 2025
64 of 65 checks passed
@ronamironami deleted the no-for-in-array-nullish branchJanuary 19, 2025 21:03
renovatebot added a commit to mmkal/eslint-plugin-mmkal that referenced this pull requestJan 21, 2025
##### [v8.21.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8210-2025-01-20)##### 🩹 Fixes-   **eslint-plugin:** \[no-duplicate-enum-values] handle template literal ([#10675](typescript-eslint/typescript-eslint#10675))-   **eslint-plugin:** \[no-base-to-string] don't crash for recursive array or tuple types ([#10633](typescript-eslint/typescript-eslint#10633))-   **eslint-plugin:** \[no-for-in-array] report on any type which may be an array or array-like ([#10535](typescript-eslint/typescript-eslint#10535))-   **eslint-plugin:** check JSX spread elements for misused spread usage ([#10653](typescript-eslint/typescript-eslint#10653))-   **eslint-plugin:** \[no-unnecessary-type-arguments] handle type args on jsx ([#10630](typescript-eslint/typescript-eslint#10630))##### ❤️ Thank You-   Ronen Amiel-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
renovatebot added a commit to mmkal/eslint-plugin-mmkal that referenced this pull requestJan 21, 2025
##### [v8.21.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8210-2025-01-20)##### 🩹 Fixes-   **eslint-plugin:** \[no-duplicate-enum-values] handle template literal ([#10675](typescript-eslint/typescript-eslint#10675))-   **eslint-plugin:** \[no-base-to-string] don't crash for recursive array or tuple types ([#10633](typescript-eslint/typescript-eslint#10633))-   **eslint-plugin:** \[no-for-in-array] report on any type which may be an array or array-like ([#10535](typescript-eslint/typescript-eslint#10535))-   **eslint-plugin:** check JSX spread elements for misused spread usage ([#10653](typescript-eslint/typescript-eslint#10653))-   **eslint-plugin:** \[no-unnecessary-type-arguments] handle type args on jsx ([#10630](typescript-eslint/typescript-eslint#10630))##### ❤️ Thank You-   Ronen Amiel-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
renovatebot added a commit to andrei-picus-tink/auto-renovate that referenced this pull requestJan 24, 2025
| datasource | package                          | from   | to     || ---------- | -------------------------------- | ------ | ------ || npm        | @typescript-eslint/eslint-plugin | 8.20.0 | 8.21.0 || npm        | @typescript-eslint/parser        | 8.20.0 | 8.21.0 |## [v8.21.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8210-2025-01-20)##### 🩹 Fixes-   **eslint-plugin:** \[no-duplicate-enum-values] handle template literal ([#10675](typescript-eslint/typescript-eslint#10675))-   **eslint-plugin:** \[no-base-to-string] don't crash for recursive array or tuple types ([#10633](typescript-eslint/typescript-eslint#10633))-   **eslint-plugin:** \[no-for-in-array] report on any type which may be an array or array-like ([#10535](typescript-eslint/typescript-eslint#10535))-   **eslint-plugin:** check JSX spread elements for misused spread usage ([#10653](typescript-eslint/typescript-eslint#10653))-   **eslint-plugin:** \[no-unnecessary-type-arguments] handle type args on jsx ([#10630](typescript-eslint/typescript-eslint#10630))##### ❤️ Thank You-   Ronen Amiel-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
renovatebot added a commit to andrei-picus-tink/auto-renovate that referenced this pull requestJan 24, 2025
| datasource | package                          | from   | to     || ---------- | -------------------------------- | ------ | ------ || npm        | @typescript-eslint/eslint-plugin | 8.20.0 | 8.21.0 || npm        | @typescript-eslint/parser        | 8.20.0 | 8.21.0 |## [v8.21.0](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#8210-2025-01-20)##### 🩹 Fixes-   **eslint-plugin:** \[no-duplicate-enum-values] handle template literal ([#10675](typescript-eslint/typescript-eslint#10675))-   **eslint-plugin:** \[no-base-to-string] don't crash for recursive array or tuple types ([#10633](typescript-eslint/typescript-eslint#10633))-   **eslint-plugin:** \[no-for-in-array] report on any type which may be an array or array-like ([#10535](typescript-eslint/typescript-eslint#10535))-   **eslint-plugin:** check JSX spread elements for misused spread usage ([#10653](typescript-eslint/typescript-eslint#10653))-   **eslint-plugin:** \[no-unnecessary-type-arguments] handle type args on jsx ([#10630](typescript-eslint/typescript-eslint#10630))##### ❤️ Thank You-   Ronen Amiel-   YeonJuan [@yeonjuan](https://github.com/yeonjuan)You can read about our [versioning strategy](https://main--typescript-eslint.netlify.app/users/versioning) and [releases](https://main--typescript-eslint.netlify.app/users/releases) on our website.
@github-actionsgithub-actionsbot locked asresolvedand limited conversation to collaboratorsJan 27, 2025
Sign up for freeto subscribe to this conversation on GitHub. Already have an account?Sign in.
Reviewers

@JoshuaKGoldbergJoshuaKGoldbergJoshuaKGoldberg approved these changes

@kirkwaiblingerkirkwaiblingerkirkwaiblinger approved these changes

Assignees
No one assigned
Labels
1 approval>=1 team member has approved this PR; we're now leaving it open for more reviews before we merge
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

Bug: [no-for-in-array] fails to report onArray<T> | undefined
3 participants
@ronami@kirkwaiblinger@JoshuaKGoldberg

[8]ページ先頭

©2009-2025 Movatter.jp