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-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
Merged
Show file tree
Hide file tree
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
StyleShitDec 14, 2023
1a81329
small refactor
StyleShitDec 14, 2023
8ecf59f
Merge remote-tracking branch 'typescript-eslint/main' into feat/no-ar…
StyleShitDec 16, 2023
6d098b8
add more cases
StyleShitDec 17, 2023
a44d957
fix docs
StyleShitDec 17, 2023
36250a9
fix message
StyleShitDec 17, 2023
80e61fc
use suggestion instead of fix
StyleShitDec 30, 2023
4b29b59
added more test cases
StyleShitDec 30, 2023
0d9642f
Merge branch 'main' into feat/no-array-delete
StyleShitDec 30, 2023
00d7d51
Merge branch 'main' into feat/no-array-delete
StyleShitJan 4, 2024
ac595ca
remove redundant condition
StyleShitJan 7, 2024
e12f901
keep comments
StyleShitJan 7, 2024
0004c10
Merge remote-tracking branch 'typescript-eslint/main' into feat/no-ar…
StyleShitJan 7, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletionspackages/eslint-plugin/docs/rules/no-array-delete.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,6 +39,7 @@ export = {
'@typescript-eslint/naming-convention': 'error',
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'error',
'@typescript-eslint/no-array-delete': 'error',
'@typescript-eslint/no-base-to-string': 'error',
'@typescript-eslint/no-confusing-non-null-assertion': 'error',
'@typescript-eslint/no-confusing-void-expression': 'error',
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@ export = {
'@typescript-eslint/consistent-type-exports': 'off',
'@typescript-eslint/dot-notation': 'off',
'@typescript-eslint/naming-convention': 'off',
'@typescript-eslint/no-array-delete': 'off',
'@typescript-eslint/no-base-to-string': 'off',
'@typescript-eslint/no-confusing-void-expression': 'off',
'@typescript-eslint/no-duplicate-type-constituents': 'off',
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,6 +13,7 @@ export = {
'@typescript-eslint/ban-types': 'error',
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'error',
'@typescript-eslint/no-array-delete': 'error',
'@typescript-eslint/no-base-to-string': 'error',
'@typescript-eslint/no-confusing-void-expression': 'error',
'@typescript-eslint/no-duplicate-enum-values': 'error',
Expand Down
2 changes: 2 additions & 0 deletionspackages/eslint-plugin/src/rules/index.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,6 +34,7 @@ import memberOrdering from './member-ordering';
import methodSignatureStyle from './method-signature-style';
import namingConvention from './naming-convention';
import noArrayConstructor from './no-array-constructor';
import noArrayDelete from './no-array-delete';
import noBaseToString from './no-base-to-string';
import confusingNonNullAssertionLikeNotEqual from './no-confusing-non-null-assertion';
import noConfusingVoidExpression from './no-confusing-void-expression';
Expand DownExpand Up@@ -173,6 +174,7 @@ export default {
'method-signature-style': methodSignatureStyle,
'naming-convention': namingConvention,
'no-array-constructor': noArrayConstructor,
'no-array-delete': noArrayDelete,
'no-base-to-string': noBaseToString,
'no-confusing-non-null-assertion': confusingNonNullAssertionLikeNotEqual,
'no-confusing-void-expression': noConfusingVoidExpression,
Expand Down
112 changes: 112 additions & 0 deletionspackages/eslint-plugin/src/rules/no-array-delete.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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);
},
},
],
});
},
};
},
});
Loading

[8]ページ先頭

©2009-2025 Movatter.jp