Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
feat(eslint-plugin): [no-array-delete] add new rule#8067
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
JoshuaKGoldberg merged 13 commits intotypescript-eslint:mainfromStyleShit:feat/no-array-deleteJan 9, 2024
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
13 commits Select commitHold shift + click to select a range
a2b9a4a
feat(eslint-plugin): [no-array-delete] add new rule
StyleShit1a81329
small refactor
StyleShit8ecf59f
Merge remote-tracking branch 'typescript-eslint/main' into feat/no-ar…
StyleShit6d098b8
add more cases
StyleShita44d957
fix docs
StyleShit36250a9
fix message
StyleShit80e61fc
use suggestion instead of fix
StyleShit4b29b59
added more test cases
StyleShit0d9642f
Merge branch 'main' into feat/no-array-delete
StyleShit00d7d51
Merge branch 'main' into feat/no-array-delete
StyleShitac595ca
remove redundant condition
StyleShite12f901
keep comments
StyleShit0004c10
Merge remote-tracking branch 'typescript-eslint/main' into feat/no-ar…
StyleShitFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
40 changes: 40 additions & 0 deletionspackages/eslint-plugin/docs/rules/no-array-delete.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
--- | ||
description: 'Disallow using the `delete` operator on array values.' | ||
--- | ||
> 🛑 This file is source code, not the primary documentation location! 🛑 | ||
> | ||
> See **https://typescript-eslint.io/rules/no-array-delete** for documentation. | ||
When using the `delete` operator with an array value, the array's `length` property is not affected, | ||
but the element at the specified index is removed and leaves an empty slot in the array. | ||
This is likely to lead to unexpected behavior. As mentioned in the | ||
[MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#deleting_array_elements), | ||
the recommended way to remove an element from an array is by using the | ||
[`Array#splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method. | ||
## Examples | ||
<!--tabs--> | ||
### ❌ Incorrect | ||
```ts | ||
declare const arr: number[]; | ||
delete arr[0]; | ||
``` | ||
### ✅ Correct | ||
```ts | ||
declare const arr: number[]; | ||
arr.splice(0, 1); | ||
``` | ||
<!--/tabs--> | ||
## When Not To Use It | ||
When you want to allow the delete operator with array expressions. |
1 change: 1 addition & 0 deletionspackages/eslint-plugin/src/configs/all.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionspackages/eslint-plugin/src/configs/disable-type-checked.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionspackages/eslint-plugin/src/configs/strict-type-checked.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletionspackages/eslint-plugin/src/rules/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletionspackages/eslint-plugin/src/rules/no-array-delete.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; | ||
import { AST_NODE_TYPES, AST_TOKEN_TYPES } from '@typescript-eslint/utils'; | ||
import { getSourceCode } from '@typescript-eslint/utils/eslint-utils'; | ||
import type * as ts from 'typescript'; | ||
import { | ||
createRule, | ||
getConstrainedTypeAtLocation, | ||
getParserServices, | ||
} from '../util'; | ||
type MessageId = 'noArrayDelete' | 'useSplice'; | ||
export default createRule<[], MessageId>({ | ||
name: 'no-array-delete', | ||
meta: { | ||
hasSuggestions: true, | ||
type: 'problem', | ||
docs: { | ||
description: 'Disallow using the `delete` operator on array values', | ||
recommended: 'strict', | ||
requiresTypeChecking: true, | ||
}, | ||
messages: { | ||
noArrayDelete: | ||
'Using the `delete` operator with an array expression is unsafe.', | ||
useSplice: 'Use `array.splice()` instead.', | ||
}, | ||
schema: [], | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
const services = getParserServices(context); | ||
const checker = services.program.getTypeChecker(); | ||
function isUnderlyingTypeArray(type: ts.Type): boolean { | ||
const predicate = (t: ts.Type): boolean => | ||
checker.isArrayType(t) || checker.isTupleType(t); | ||
if (type.isUnion()) { | ||
return type.types.every(predicate); | ||
} | ||
if (type.isIntersection()) { | ||
return type.types.some(predicate); | ||
} | ||
return predicate(type); | ||
} | ||
return { | ||
'UnaryExpression[operator="delete"]'( | ||
node: TSESTree.UnaryExpression, | ||
): void { | ||
const { argument } = node; | ||
if (argument.type !== AST_NODE_TYPES.MemberExpression) { | ||
return; | ||
} | ||
const type = getConstrainedTypeAtLocation(services, argument.object); | ||
if (!isUnderlyingTypeArray(type)) { | ||
return; | ||
} | ||
context.report({ | ||
node, | ||
messageId: 'noArrayDelete', | ||
suggest: [ | ||
{ | ||
messageId: 'useSplice', | ||
fix(fixer): TSESLint.RuleFix | null { | ||
const { object, property } = argument; | ||
const shouldHaveParentheses = | ||
property.type === AST_NODE_TYPES.SequenceExpression; | ||
const nodeMap = services.esTreeNodeToTSNodeMap; | ||
const target = nodeMap.get(object).getText(); | ||
const rawKey = nodeMap.get(property).getText(); | ||
const key = shouldHaveParentheses ? `(${rawKey})` : rawKey; | ||
let suggestion = `${target}.splice(${key}, 1)`; | ||
const sourceCode = getSourceCode(context); | ||
const comments = sourceCode.getCommentsInside(node); | ||
if (comments.length > 0) { | ||
const indentationCount = node.loc.start.column; | ||
const indentation = ' '.repeat(indentationCount); | ||
const commentsText = comments | ||
.map(comment => { | ||
return comment.type === AST_TOKEN_TYPES.Line | ||
? `//${comment.value}` | ||
: `/*${comment.value}*/`; | ||
}) | ||
.join(`\n${indentation}`); | ||
suggestion = `${commentsText}\n${indentation}${suggestion}`; | ||
} | ||
return fixer.replaceText(node, suggestion); | ||
}, | ||
}, | ||
], | ||
}); | ||
}, | ||
}; | ||
}, | ||
}); |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.