Skip to content

feat(eslint-plugin): [no-misused-object-like] add rule #9369

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

gibson
Copy link

@gibson gibson commented Jun 17, 2024

PR Checklist

Overview

This MR will close the problem with usage Object.keys(), Object.values() and Object.entries() for object like classes Map and Set. On this classes that methods always returns empty array instead of any meaningful data and doesn't cause and warnings or errors

@typescript-eslint
Copy link
Contributor

Thanks for the PR, @gibson!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏 Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently on https://opencollective.com/typescript-eslint.

Copy link

netlify bot commented Jun 17, 2024

Deploy Preview for typescript-eslint failed.

Name Link
🔨 Latest commit 716096d
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/666feffa052e5400085851b4

Copy link

nx-cloud bot commented Jun 17, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 716096d. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


✅ Successfully ran 1 target

Sent with 💌 from NxCloud.

@SimonSchick
Copy link

SimonSchick commented Jun 21, 2024

This is missing support for ReadonlyMap ReadonlySet, WeakMap and WeakSet (and possibly others) and will likely not work with inheritance?

It may be worth-while to check if the subject of the check has any .get(arg) and .set(arg1, arg2) methods to catch issues with Headers and friends as well, this may be slow however.

> new Headers({a:1})
Headers { a: '1' }
> Object.values(new Headers({a:1}))
[]
> Object.entries(new Headers({a:1}))
[]

Overall this is a good PR, it might also be good to integrate #5677 into this and generalize this rule as no-misused-map-like-usage?

Copy link

Uh oh! @SimonSchick, the image you shared is missing helpful alt text. Check #9369 (comment).

Alt text is an invisible description that helps screen readers describe images to blind or low-vision users. If you are using markdown to display images, add your alt text inside the brackets of the markdown image.

Learn more about alt text at Basic writing and formatting syntax: images on GitHub Docs.

🤖 Beep boop! This comment was added automatically by github/accessibility-alt-text-bot.

Copy link

@SimonSchick SimonSchick left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be extremely useful when migrating from object dictionary use to map/set use!

requiresTypeChecking: false,
},
messages: {
objectKeysForMap: "Don't use `Object.keys()` for Map objects",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this may be overly specific, granularity for SetLike and MapLike is likely sufficient since it would be weird to allow calling Object.values( on a Map but banning Object.keys

docs: {
description:
'Enforce check `Object.values(...)`, `Object.keys(...)`, `Object.entries(...)` usage with Map/Set objects',
requiresTypeChecking: false,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure this is required?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, the services.getTypeAtLocation below necessitates it.

}

return {
'CallExpression[callee.object.name=Object][callee.property.name=keys][arguments.length=1]':

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is missing various other ones such as Object.assign/groupBy/hasOwn?, it might be better to move this check into the checkObjectMethodCall function and have a list of banned methods there.

checkObjectValuesForSet?: boolean;
checkObjectEntriesForSet?: boolean;
},
];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Question] Why allow such a granular set of options? Is there a known use case where someone would want to skip, say, only Object.values?

Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good start! There are some functional gaps that'll need to be filled in around more object support and resiliency to user shenanigans. Excited to see this - thanks for getting it started! 🙌

const callee = callExpression.callee as MemberExpression;
const objectMethod = (callee.property as Identifier).name;

if (argumentTypeName === 'Map') {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] If a user defines their own Map class, this will falsely report:

class Map {
  value = 1;
}

const map = new Map();
Object.values(map);

Comment on lines +95 to +96
const callee = callExpression.callee as MemberExpression;
const objectMethod = (callee.property as Identifier).name;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] Using an as assertion on AST nodes is generally a sign of either:

  • 🍎 The node is known to be a more specific type than what you've told the type system
  • 🍌 The code isn't properly handling edge cases

The CallExpression[callee.object.name=Object][callee.property.name=keys][arguments.length=1] below makes me think it's 🍎. Which means you'd want to use a type for the node.

    type CallExpressionWithStuff = TSESTree.CallExpression & {
      callee: {
        object: {
          name: 'Object';
      // ...

}

return {
'CallExpression[callee.object.name=Object][callee.property.name=keys][arguments.length=1]':
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

object.name=Object

[Bug] False report case:

const Object = { keys: (value) => [value] };

export const keys = Object.keys(new Map());

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Testing] Some missing test cases:

  • Intersections and unions: with Map, Set, and/or other types
  • Readonlies: ReadonlyMap, ReadonlySet

}
}

return {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] Looking at built-in global objects in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects#keyed_collections, I think at least WeakMap and WeakSet should also be handled by this rule.

@JoshuaKGoldberg JoshuaKGoldberg added the awaiting response Issues waiting for a reply from the OP or another party label Jun 27, 2024
@SimonSchick
Copy link

@gibson are you interested in continuing work on this? Otherwise I may be inclined to take a stab at this myself.

@gibson
Copy link
Author

gibson commented Jul 10, 2024

@SimonSchick will continue in closes time

@JoshuaKGoldberg
Copy link
Member

👋 @gibson just checking in, do you still plan on working on this?

@JoshuaKGoldberg JoshuaKGoldberg added the stale PRs or Issues that are at risk of being or have been closed due to inactivity for a prolonged period label Aug 12, 2024
@bradzacher bradzacher changed the title #6807 Prevent misusage of Object.keys(), Object.values(), Ob feat(eslint-plugin): [no-misused-object-like] add rule Aug 25, 2024
@JoshuaKGoldberg
Copy link
Member

Closing this PR as it's been stale for ~6 weeks without activity. Feel free to reopen @gibson if you have time - but no worries if not! If anybody wants to drive it forward, please do post your own PR - and if you use this as a start, consider adding Co-authored-by: @gibson at the end of your PR description. Thanks! 😊

@SimonSchick
Copy link

I might pick this up, I ran into some scenarious/migrations where this rule would've been incredibly valuable.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Sep 2, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
awaiting response Issues waiting for a reply from the OP or another party stale PRs or Issues that are at risk of being or have been closed due to inactivity for a prolonged period
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Rule proposal: Prevent Object.values(...) usage with Map
3 participants