Skip to content

Enhancement: [no-unsafe-enum-comparison] Add option to allow comparing left-side primitive values with right-side enum values #7219

Closed as not planned
@DanielRose

Description

@DanielRose

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-unsafe-enum-comparison/

Description

In our codebase, in various places we have values which are typed as string. This can be due to control/component limitations, or because they are coming from the database, or because they are partially user-defined (ie. there are standard values and custom values).

We place the "known values" or "standard values" in a string enum, and do comparisons with these known values to handle them, with the user-provided value on the left side and the known enum value on the right side.

This is now an error due to no-unsafe-enum-comparison. At the same time, this rule has found places where we did incorrect comparisons, so we don't want to disable the rule.

The proposal would be to add an option to allow a comparison between a primitive value (string/number) on the left side, and an enum value of the same type on the right side. Any other comparisons would still be an error.

Fail

enum KnownVegetable {
  Asparagus = 'asparagus',
}

declare let vegetable: KnownVegetable;
declare let apiVegetable: string;

vegetable === 'asparagus';
KnownVegetable.Asparagus === apiVegetable; // still not allowed: primitive value must be on left side

Pass

enum KnownVegetable {
  Asparagus = 'asparagus',
}

declare let vegetable: KnownVegetable;
declare let apiVegetable: string;

vegetable === KnownVegetable.Asparagus;
apiVegetable === KnownVegetable.Asparagus; // now allowed: primitive value on left side compared with enum value on right side

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-pluginwontfixThis will not be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions