Skip to content

Commit

Permalink
fix(eslint-plugin-react-hooks): accepting as expressions as deps ar…
Browse files Browse the repository at this point in the history
…ray (facebook#28189)

## Summary

This PR closes facebook#25844
The original issue talks about `as const`, but seems like it fails for
any `as X` expressions since it adds another nesting level to the AST.

EDIT: Also closes facebook#20162

## How did you test this change?

Added unit tests
  • Loading branch information
StyleShit authored and AndyPengc12 committed Apr 15, 2024
1 parent 5124588 commit a1c219d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7747,6 +7747,24 @@ const testsTypescript = {
}
`,
},
{
code: normalizeIndent`
function App(props) {
React.useEffect(() => {
console.log(props.test);
}, [props.test] as const);
}
`,
},
{
code: normalizeIndent`
function App(props) {
React.useEffect(() => {
console.log(props.test);
}, [props.test] as any);
}
`,
},
],
invalid: [
{
Expand Down
13 changes: 11 additions & 2 deletions packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,12 @@ export default {

const declaredDependencies = [];
const externalDependencies = new Set();
if (declaredDependenciesNode.type !== 'ArrayExpression') {
const isArrayExpression =
declaredDependenciesNode.type === 'ArrayExpression';
const isTSAsArrayExpression =
declaredDependenciesNode.type === 'TSAsExpression' &&
declaredDependenciesNode.expression.type === 'ArrayExpression';
if (!isArrayExpression && !isTSAsArrayExpression) {
// If the declared dependencies are not an array expression then we
// can't verify that the user provided the correct dependencies. Tell
// the user this in an error.
Expand All @@ -631,7 +636,11 @@ export default {
'dependencies.',
});
} else {
declaredDependenciesNode.elements.forEach(declaredDependencyNode => {
const arrayExpression = isTSAsArrayExpression
? declaredDependenciesNode.expression
: declaredDependenciesNode;

arrayExpression.elements.forEach(declaredDependencyNode => {
// Skip elided elements.
if (declaredDependencyNode === null) {
return;
Expand Down

0 comments on commit a1c219d

Please sign in to comment.