Skip to content

Enhancement: [no-unnecessary-condition] Add option to disable switch statement checks #11448

@fkuriataGH

Description

@fkuriataGH

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Link to the rule's documentation

https://typescript-eslint.io/rules/no-unnecessary-condition/

Description

There’s a minor issue when using the rules switch-exhaustiveness-check and no-unnecessary-condition together.

Example:

type ProductCategory = "Food"

function getProduct(category: ProductCategory) {
  switch (category) { // same issue applies to `if` statements
    case "Food":
      return "Something meaningful"
  }
}

In this case, ESLint reports:

Unnecessary conditional, comparison is always true. Both sides of the comparison always have a literal type.

Of course, I can refactor it to:

function getProduct(category: ProductCategory) {
  return "Something meaningful"
}

It's technically correct, but in practice, the code is less type-safe. For example, if the ProductCategory type evolves:

type ProductCategory = "Food" | "Drink"

// thanks to `switch-exhaustiveness-check`, I would immediately know I need to handle the new case
function getProduct(category: ProductCategory) {
  switch (category) {
    case "Food":
      return "Something meaningful"
  }
}

// but if someone had previously refactored it to:
function getProduct(category: ProductCategory) {
  return "Something meaningful"
}
// The new case "Drink" would be silently ignored — no type error, no ESLint warning.

Suggestion

These two rules are great and I wouldn't want to disable either of them entirely.

Would it be possible to add an option to disable no-unnecessary-condition only for switch statements? Or maybe there is another way to deal with it?

For now, the only workaround I’ve found is to:

  • Write a custom rule, or
  • Manually disable no-unnecessary-condition for every switch with only one possible value.

Fail

function getProduct(perPage: number) {
  const limit = perPage ?? 5; // fail
  // ... do something
}

function getProduct(category: 'food') {
  if (category === 'food') {
        return "Something meaningful"
  }
}

Pass

function getProduct(category: 'food') {
  switch (category) {
      case 'food':
        return "Something meaningful"
  }
}

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement: plugin rule optionNew rule option for an existing eslint-plugin rulepackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugintriageWaiting for team members to take a look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions