🌐 AI搜索 & 代理 主页
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
description: 'Disallow using Object.keys, Object.values, and Object.entries on Map and Set instances.'
---

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-object-methods-on-collections** for documentation.

Methods like `Object.entries()`, `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 deletions packages/eslint-plugin/src/configs/eslintrc/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export = {
'@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-object-methods-on-collections': 'error',
'no-redeclare': 'off',
'@typescript-eslint/no-redeclare': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export = {
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-misused-spread': 'off',
'@typescript-eslint/no-mixed-enums': 'off',
'@typescript-eslint/no-object-methods-on-collections': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off',
'@typescript-eslint/no-unnecessary-condition': 'off',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/flat/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export default (
'@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-object-methods-on-collections': 'error',
'no-redeclare': 'off',
'@typescript-eslint/no-redeclare': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default (
'@typescript-eslint/no-misused-promises': 'off',
'@typescript-eslint/no-misused-spread': 'off',
'@typescript-eslint/no-mixed-enums': 'off',
'@typescript-eslint/no-object-methods-on-collections': 'off',
'@typescript-eslint/no-redundant-type-constituents': 'off',
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off',
'@typescript-eslint/no-unnecessary-condition': 'off',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import noNamespace from './no-namespace';
import noNonNullAssertedNullishCoalescing from './no-non-null-asserted-nullish-coalescing';
import noNonNullAssertedOptionalChain from './no-non-null-asserted-optional-chain';
import noNonNullAssertion from './no-non-null-assertion';
import noObjectMethodsOnCollections from './no-object-methods-on-collections';
import noRedeclare from './no-redeclare';
import noRedundantTypeConstituents from './no-redundant-type-constituents';
import noRequireImports from './no-require-imports';
Expand Down Expand Up @@ -192,6 +193,7 @@ const rules = {
'no-non-null-asserted-nullish-coalescing': noNonNullAssertedNullishCoalescing,
'no-non-null-asserted-optional-chain': noNonNullAssertedOptionalChain,
'no-non-null-assertion': noNonNullAssertion,
'no-object-methods-on-collections': noObjectMethodsOnCollections,
'no-redeclare': noRedeclare,
'no-redundant-type-constituents': noRedundantTypeConstituents,
'no-require-imports': noRequireImports,
Expand Down
119 changes: 119 additions & 0 deletions packages/eslint-plugin/src/rules/no-object-methods-on-collections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { ESLintUtils, AST_NODE_TYPES } from '@typescript-eslint/utils';

import { createRule } from '../util';

const COLLECTION_TYPES = ['Map', 'Set', 'WeakMap', 'WeakSet'] as const;

const ALTERNATIVES = {
'Object.assign': {
Map: 'map.set(key, value) or new Map([...map, ...otherMap])',
Set: 'set.add(value) or new Set([...set, ...otherSet])',
WeakMap: 'map.set(key, value)',
WeakSet: 'set.add(value)',
},
'Object.entries': {
Map: 'Array.from(map.entries())',
Set: 'Array.from(set.entries())',
WeakMap: 'Array.from(map.entries())',
WeakSet: 'Array.from(set.entries())',
},
'Object.keys': {
Map: 'Array.from(map.keys())',
Set: 'Array.from(set.values())',
WeakMap: 'Array.from(map.keys())',
WeakSet: 'Array.from(set.values())',
},
'Object.values': {
Map: 'Array.from(map.values())',
Set: 'Array.from(set.values())',
WeakMap: 'Array.from(map.values())',
WeakSet: 'Array.from(set.values())',
},
};

export default createRule({
name: 'no-object-methods-on-collections',
meta: {
type: 'problem',
docs: {
description: 'Disallow using Object methods on Map and Set instances',
requiresTypeChecking: true,
},
messages: {
noObjectMethodsOnCollections:
'Using {{method}}() on a {{type}} is incorrect. Use {{alternative}} instead.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const parserServices = ESLintUtils.getParserServices(context);
const checker = parserServices.program.getTypeChecker();

return {
CallExpression(node) {
// Is it Object.keys/values/entries/assign() call?
if (
node.callee.type !== AST_NODE_TYPES.MemberExpression ||
node.callee.object.type !== AST_NODE_TYPES.Identifier ||
node.callee.object.name !== 'Object' ||
node.callee.property.type !== AST_NODE_TYPES.Identifier ||
!['keys', 'values', 'entries', 'assign'].includes(
node.callee.property.name,
)
) {
return;
}

const methodName = node.callee.property.name;

// For keys/values/entries, we need exactly 1 argument
// For assign, we need at least 1 argument (the target)
if (methodName === 'assign') {
if (node.arguments.length < 1) {
return;
}
} else {
if (node.arguments.length !== 1) {
return;
}
}

// Get argument type as a string
const argument = node.arguments[0];
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(argument);
const type = checker.getTypeAtLocation(tsNode);
const typeString = checker.typeToString(type);

// Skip unknown types
if (typeString === 'any' || typeString === 'unknown') {
return;
}

// Is the argument a collection type?
const collectionType = COLLECTION_TYPES.find(t =>
typeString.includes(t),
);
if (!collectionType) {
return;
}

const fullMethodName =
`Object.${methodName}` as keyof typeof ALTERNATIVES;
const alternative =
ALTERNATIVES[fullMethodName][collectionType] ||
`the ${collectionType}'s own methods`;

context.report({
node,
messageId: 'noObjectMethodsOnCollections',
data: {
type: collectionType,
alternative,
method: fullMethodName,
},
});
},
};
},
});

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { RuleTester } from '@typescript-eslint/rule-tester';

import rule from '../../src/rules/no-object-methods-on-collections';
import { getFixturesRootDir } from '../RuleTester';

const rootDir = getFixturesRootDir();

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

ruleTester.run('no-object-methods-on-collections', rule, {
valid: [
{
code: `
const test = {};
Object.entries(test);
`,
},
{
code: `
const test = {};
Object.keys(test);
`,
},
{
code: `
const test = {};
Object.values(test);
`,
},
{
code: `
const test = [];
Object.keys(test);
`,
},
{
code: `
const test = [];
Object.values(test);
`,
},
{
code: `
const test = [];
Object.entries(test);
`,
},
{
code: `
const test = 123;
Object.keys(test);
`,
},
{
code: `
const obj = {};
Object.assign(obj, { key: 'value' });
`,
},
{
code: `
const arr = [];
Object.assign(arr, { key: 'value' });
`,
},
],
invalid: [
{
code: `
const map = new Map();
const result = Object.keys(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const map = new Map();
const result = Object.entries(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const map = new Map();
const result = Object.values(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const set = new Set();
const result = Object.keys(set);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const set = new Set();
const result = Object.entries(set);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const set = new Set();
const result = Object.values(set);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
class ExMap extends Map {}
const map = new ExMap();
Object.keys(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
class ExMap extends Map {}
const map = new ExMap();
Object.values(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
class ExMap extends Map {}
const map = new ExMap();
Object.entries(map);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const test = new WeakMap();
Object.keys(test);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const test = new WeakSet();
Object.values(test);
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const map = new Map();
Object.assign(map, { key: 'value' });
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const set = new Set();
Object.assign(set, { key: 'value' });
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const map = new WeakMap();
Object.assign(map, { key: 'value' });
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
{
code: `
const set = new WeakSet();
Object.assign(set, { key: 'value' });
`,
errors: [{ messageId: 'noObjectMethodsOnCollections' }],
},
],
});
Loading
Loading