sindresorhus/eslint-plugin-unicorn

The `prefer-switch` rule can behave strangely in certain situations

Open

#2,564 建立於 2025年2月19日

在 GitHub 查看
 (4 留言) (0 反應) (0 負責人)JavaScript (5,022 star) (468 fork)user submission
change requesthelp wanted

描述

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.

貢獻者指南

The `prefer-switch` rule can behave strangely in certain situations · sindresorhus/eslint-plugin-unicorn#2564 | Good First Issue