Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
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
fix(eslint-plugin): [no-for-in-array] report on any type which may be an array or array-like#10535
Uh oh!
There was an error while loading.Please reload this page.
Conversation
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-cloudbot commentedDec 21, 2024 • 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.
View yourCI Pipeline Execution ↗ for commit599ac75.
☁️Nx Cloud last updated this comment at |
netlifybot commentedDec 21, 2024 • 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 configuration. |
codecovbot commentedDec 21, 2024 • 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 ReportAll modified and coverable lines are covered by tests ✅
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
Flags with carried forward coverage won't be shown.Click here to find out more.
|
@@ -45,3 +45,20 @@ export default createRule({ | |||
}; | |||
}, | |||
}); | |||
function isTypeArrayTypeOrUnionOfArrayTypes( |
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.
(style) avoid having the identical name function but with different behavior compared to theisTypeArrayTypeOrUnionOfArrayTypes
in utils?
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; |
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.
(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.
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)) | |
); |
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.
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.
Requesting changes here just to account for conversation on the backing issue#10534 (comment)
ronami commentedDec 27, 2024 • 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.
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 as Remaining things that I think may benefit the rule (I'll consider opening issues for these):
Thanks@kirkwaiblinger 👍 |
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); | ||
} |
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.
I've used this part from#10551.
Uh oh!
There was an error while loading.Please reload this page.
'IArguments', | ||
'HTMLCollection', | ||
'RegExpExecArray', | ||
'NodeList', |
ronamiDec 28, 2024 • edited by kirkwaiblinger
Loading Uh oh!
There was an error while loading.Please reload this page.
edited by kirkwaiblinger
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.
I'm not an expert on array-likes, basing this onhttps://developer.mozilla.org/en-US/docs/Web/API/NodeList.
return isTypeRecurser(type, t => | ||
isBuiltinSymbolLike(program, t, [ | ||
'IArguments', | ||
'HTMLCollection', |
ronamiDec 28, 2024 • edited by kirkwaiblinger
Loading Uh oh!
There was an error while loading.Please reload this page.
edited by kirkwaiblinger
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.
I'm not an expert on array-likes, basing this onhttps://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.
{ | ||
"extends": "./tsconfig.json", | ||
"compilerOptions": { | ||
"lib": ["es2015", "es2017", "esnext", "dom"] | ||
} | ||
} |
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.
Is there a better way to do this? Specificallydom
is necessary for the two dom-array-likes.
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.
Yep, this is good!
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 👍 |
@@ -45,3 +42,32 @@ export default createRule({ | |||
}; | |||
}, | |||
}); | |||
function isArrayLike(program: ts.Program, type: ts.Type): boolean { |
kirkwaiblingerJan 7, 2025 • 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.
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?
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.
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 👍
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.
I'm happy!
JoshuaKGoldberg 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.
+1, this is sweet. 🍬
74f1c5a
intotypescript-eslint:mainUh oh!
There was an error while loading.Please reload this page.
##### [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.
##### [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.
| 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.
| 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.
Uh oh!
There was an error while loading.Please reload this page.
PR Checklist
Array<T> | undefined
#10534Overview
See#10535 (comment) for the updated contents of this PR.
This PR tackles#10534 and reports on cases such as: