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-misused-object-likes] add rule#10104

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

Closed
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
15 commits
Select commitHold shift + click to select a range
1f024a2
bring previous PR
abrahamguoSep 19, 2024
0e39ae1
cleanup
abrahamguoSep 19, 2024
b08e8a5
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into n…
abrahamguoOct 4, 2024
54cd241
fix TS error and support readonly
abrahamguoOct 4, 2024
813dd7d
update description
abrahamguoOct 4, 2024
ad28a4a
generate-configs
abrahamguoOct 6, 2024
c0ba704
add docs page
abrahamguoOct 7, 2024
139d0e7
WIP
abrahamguoOct 8, 2024
0af7510
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into n…
abrahamguoOct 8, 2024
c1ebe07
implement 'in' operator
abrahamguoOct 8, 2024
605c8e2
lint
abrahamguoOct 8, 2024
0ccee09
check whether symbol is from default library
abrahamguoOct 8, 2024
a5658fd
WIP
abrahamguoOct 10, 2024
2d21b9a
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into n…
abrahamguoOct 17, 2024
8dec282
lint
abrahamguoOct 17, 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
34 changes: 34 additions & 0 deletionspackages/eslint-plugin/docs/rules/no-misused-object-likes.mdx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
---
description: 'Disallow using `Object.{assign|entries|hasOwn|keys|values}(...)` and the `in` operator on Map/Set objects.'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-misused-object-likes** for documentation.

Methods like `Object.assign()`, `Object.entries()`, `Object.hasOwn()`, `Object.keys()`, and `Object.values()` can be
used work with collections of data stored in objects. However, when working with `Map` or `Set` objects, even though
they are collections, using these methods are a mistake because they do not properly write to (in the case of
`Object.assign()`) or read from the object.

This rule prevents such methods from being used on `Map` and `Set` objects.

<Tabs>
<TabItem value="❌ Incorrect">
```ts
console.log(Object.values(new Set('abc')));
Object.assign(new Map(), { k: 'v' });
```
</TabItem>
<TabItem value="✅ Correct">
```ts
console.log([...new Set('abc').values()]);
new Map().set('k', 'v');
```
</TabItem>
</Tabs>

{/* Intentionally Omitted: When Not To Use It */}
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@@ -73,6 +73,7 @@ export = {
'@typescript-eslint/no-magic-numbers': 'error',
'@typescript-eslint/no-meaningless-void-operator': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-misused-object-likes': 'error',
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/no-mixed-enums': 'error',
'@typescript-eslint/no-namespace': 'error',
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -24,6 +24,7 @@ export = {
'@typescript-eslint/no-for-in-array': 'off',
'@typescript-eslint/no-implied-eval': 'off',
'@typescript-eslint/no-meaningless-void-operator': 'off',
'@typescript-eslint/no-misused-object-likes': 'off',
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-mixed-enums': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
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@@ -52,6 +52,7 @@ import noLossOfPrecision from './no-loss-of-precision';
import noMagicNumbers from './no-magic-numbers';
import noMeaninglessVoidOperator from './no-meaningless-void-operator';
import noMisusedNew from './no-misused-new';
import noMisusedObjectLikes from './no-misused-object-likes';
import noMisusedPromises from './no-misused-promises';
import noMixedEnums from './no-mixed-enums';
import noNamespace from './no-namespace';
Expand DownExpand Up@@ -181,6 +182,7 @@ const rules = {
'no-magic-numbers': noMagicNumbers,
'no-meaningless-void-operator': noMeaninglessVoidOperator,
'no-misused-new': noMisusedNew,
'no-misused-object-likes': noMisusedObjectLikes,
'no-misused-promises': noMisusedPromises,
'no-mixed-enums': noMixedEnums,
'no-namespace': noNamespace,
Expand Down
80 changes: 80 additions & 0 deletionspackages/eslint-plugin/src/rules/no-misused-object-likes.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import type { TSESTree } from '@typescript-eslint/utils';
import type * as ts from 'typescript';

import { isSymbolFromDefaultLibrary } from '@typescript-eslint/type-utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import {
createRule,
getParserServices,
getStaticMemberAccessValue,
} from '../util';

const METHODS = ['assign', 'entries', 'hasOwn', 'keys', 'values'];

export default createRule({
name: 'no-misused-object-likes',
meta: {
type: 'problem',
docs: {
description: `Disallow using \`Object.{${METHODS.join(`|`)}}(...)\` and the \`in\` operator on Map/Set objects`,
requiresTypeChecking: true,
},
messages: {
misusedObjectLike:
"Don't use {{used}} on {{objectClass}} objects — it will not properly check the contents.",
},
schema: [],
},
defaultOptions: [],

create(context) {
const getSymbolIfFromDefaultLibrary = (
node: TSESTree.Node,
): ts.Symbol | undefined => {
const services = getParserServices(context);
const symbol = services.getTypeAtLocation(node).getSymbol();
return isSymbolFromDefaultLibrary(services.program, symbol)
? symbol
: undefined;
};
const checkClassAndReport = (node: TSESTree.Node, used: string): void => {
const objectClass = getSymbolIfFromDefaultLibrary(node)?.name;
if (objectClass && /^(Readonly|Weak)?(Map|Set)$/.test(objectClass)) {
context.report({
node,
messageId: 'misusedObjectLike',
data: { objectClass, used },
});
}
};
return {
BinaryExpression(node): void {
if (node.operator === 'in') {
checkClassAndReport(node.right, 'the `in` operator');
}
},
CallExpression(node): void {
const { arguments: args, callee } = node;
if (
args.length !== 1 ||
callee.type !== AST_NODE_TYPES.MemberExpression
) {
return;
}
const { object } = callee;
if (
object.type !== AST_NODE_TYPES.Identifier ||
object.name !== 'Object' ||
getSymbolIfFromDefaultLibrary(object)
) {
return;
}
const method = getStaticMemberAccessValue(callee, context);
if (typeof method === 'string' && METHODS.includes(method)) {
checkClassAndReport(args[0], `\`Object.${method}()\``);
}
},
};
},
});
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

120 changes: 120 additions & 0 deletionspackages/eslint-plugin/tests/rules/no-misused-object-likes.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
import { RuleTester } from '@typescript-eslint/rule-tester';

import rule from '../../src/rules/no-misused-object-likes';
import { getFixturesRootDir } from '../RuleTester';

const rootPath = getFixturesRootDir();

const ruleTester = new RuleTester({
languageOptions: {
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: rootPath,
},
},
});

ruleTester.run('no-misused-object-likes', rule, {
valid: [
`
class ExMap extends Map {}
const map = new ExMap();
Object.keys(map);
`,
`
class ExMap extends Map {}
const map = new ExMap();
Object.values(map);
`,
`
class ExMap extends Map {}
const map = new ExMap();
Object.entries(map);
`,
`
const test = {};
Object.entries(test);
`,
`
const test = {};
Object.keys(test);
`,
`
const test = {};
Object.values(test);
`,
`
const test = [];
Object.keys(test);
`,
`
const test = [];
Object.values(test);
`,
`
const test = [];
Object.entries(test);
`,
`
const test = 123;
Object.keys(test);
`,
'Object.values(new (class Map {})());',
`
const Object = { keys: () => {} };
Object.keys(new Map());
`,
],
invalid: [
{
code: `
const map = new Map();
const result = Object.keys(map);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const map = new Map();
const result = Object.entries(map);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const map = new Map();
const result = Object.values(map);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const set = new Set();
const result = Object.keys(set);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const set = new Set();
const result = Object.entries(set);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const set = new Set();
const result = Object.values(set);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{
code: `
const test = new WeakMap();
Object.keys(test);
`,
errors: [{ messageId: 'misusedObjectLike' }],
},
{ code: '4 in new Set();', errors: [{ messageId: 'misusedObjectLike' }] },
],
});
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

1 change: 1 addition & 0 deletionspackages/typescript-eslint/src/configs/all.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -86,6 +86,7 @@ export default (
'@typescript-eslint/no-magic-numbers': 'error',
'@typescript-eslint/no-meaningless-void-operator': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-misused-object-likes': 'error',
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/no-mixed-enums': 'error',
'@typescript-eslint/no-namespace': 'error',
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,6 +31,7 @@ export default (
'@typescript-eslint/no-for-in-array': 'off',
'@typescript-eslint/no-implied-eval': 'off',
'@typescript-eslint/no-meaningless-void-operator': 'off',
'@typescript-eslint/no-misused-object-likes': 'off',
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-mixed-enums': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp