Skip to content
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

The prefer-switch rule can behave strangely in certain situations #2564

Open
kv-bh opened this issue Feb 19, 2025 · 1 comment
Open

The prefer-switch rule can behave strangely in certain situations #2564

kv-bh opened this issue Feb 19, 2025 · 1 comment

Comments

@kv-bh
Copy link

kv-bh commented Feb 19, 2025

The prefer-switch rule is applied in some situations where it doesn't really make sense.

Example code:

  // eslint-disable-next-line unicorn/prefer-switch
  if (typeof document.exitFullscreen === 'function') {
    await document.exitFullscreen();
  } else if (typeof document.webkitExitFullscreen === 'function') {
    await document.webkitExitFullscreen();
  } else if (typeof document.mozExitFullscreen === 'function') {
    await document.mozExitFullscreen();
  }

Example after "fixing":

  switch ('function') {
    case typeof document.exitFullscreen: {
      await document.exitFullscreen();

      break;
    }
    case typeof document.webkitExitFullscreen: {
      await document.webkitExitFullscreen();

      break;
    }
    case typeof document.mozExitFullscreen: {
      await document.mozExitFullscreen();

      break;
    }
  // No default
  }

While this may technically work, it doesn't seem like a situation where this rule should be applied. The result is unintuitive and it also causes TypeScript's type inferences to break in this situation.

@kv-bh kv-bh added the bug label Feb 19, 2025
@github-actions github-actions bot changed the title The prefer-switch rule can behave strangely in certain situations The prefer-switch rule can behave strangely in certain situations Feb 19, 2025
@fisker fisker removed the bug label Feb 19, 2025
@fisker
Copy link
Collaborator

fisker commented Feb 19, 2025

Ha, this is the first issue about switch (constant), and someone don't like my little secret, much longer than I expected to see this issue.

When I implemented this rule, I was thinking "It's fixable, so why not?"

// Compare to constant
outdent`
if (true === foo) {}
else if (bar.bar === true) {}
else if (true === baz()) {}
`,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants