Skip to content

linter: prefer-optional-chain false positive on unrelated && conditions comparing different objects #20147

@DreierF

Description

@DreierF

What version of Oxlint are you using?

1.51.0, oxlint-tsgolint 0.16.0

What command did you run?

oxlint

What does your .oxlintrc.json (or oxlint.config.ts) config file look like?

{
	"plugins": ["typescript"],
	"options": {
		"typeAware": true
	},
	"rules": {
		"typescript/prefer-optional-chain": "error"
	}
}

What happened?

typescript/prefer-optional-chain reports a false positive on a condition where two independent comparisons on different objects are joined by &&. The condition a !== X && b.prop === X.name cannot be rewritten as an optional chain because the left and right sides operate on unrelated variables.

Reproduction:

type SubjectTypeEntry = "A" | "B";

class SubjectType {
  public static readonly A = new SubjectType(0, "A");
  public static readonly B = new SubjectType(1, "B");

  private constructor(
    public readonly ordinal: number,
    public readonly name: SubjectTypeEntry,
  ) {}
}

type SubjectRoleAssignments = {
  subjectType: SubjectTypeEntry;
  subjectId: string;
};

export function createGroupInfoLabel(
  subjectRolesAssignment: SubjectRoleAssignments,
  subjectType: SubjectType,
): string {
  if (
    subjectType !== SubjectType.A &&
    subjectRolesAssignment.subjectType === SubjectType.A.name
  ) {
    return subjectRolesAssignment.subjectId;
  }
  return "";
}

Reports:

  × typescript-eslint(prefer-optional-chain): Prefer using an optional chain expression instead, as it's more concise and easier to read.
    ╭─[src/example.ts:27:5]
 26 │       if (
 27 │ ╭─▶     subjectType !== SubjectType.A &&
 28 │ ╰─▶     subjectRolesAssignment.subjectType === SubjectType.A.name
 29 │       ) {
    ╰────

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions