Skip to content

prefer-optional-chain: typeof window !== "undefined" && window.x reported; typescript-eslint excludes typeof checks on global references #1278

Done

Description

@vjeux

Description

typescript/prefer-optional-chain treats typeof window !== "undefined" (any typeof <global> !== "undefined" / === "undefined") as a nullish guard and asks for window?.…. typescript-eslint explicitly does not: a typeof check on a reference that resolves to no declaration in the file is an invalid operand (gatherLogicalOperands.ts, the isReferenceToGlobalFunction branch under ComparisonValueType.UndefinedStringLiteral), because window?.x throws a ReferenceError where typeof window !== "undefined" && window.x returns false when the global is not declared at all (SSR, workers, Node).

Versions: oxlint 1.87.0, oxlint-tsgolint 7.0.2003 (also 7.0.2004 / current main 510abce); reference @typescript-eslint/eslint-plugin 8.71.1, TypeScript 5.9.3.

Reproduction

repro.ts

export function a(): boolean {
  return typeof window !== "undefined" && window.matchMedia("(pointer: fine)").matches;
}
export function b(): boolean {
  return typeof document !== "undefined" && document.hidden;
}
export function c(): boolean {
  return typeof navigator === "undefined" || navigator.locks == null;
}

.oxlintrc.json

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

oxlint --type-aware -c .oxlintrc.json repro.ts

Actual: three prefer-optional-chain errors (lines 2, 5, 8).
Expected (typescript-eslint on the same file, same config): none.

In internal/rules/prefer_optional_chain/prefer_optional_chain.go the OperandTypeTypeofCheck operand (around L1514) is produced for any typeof x whatever x resolves to. The reference's test is "no resolved declaration in the file" (lib globals, implicit globals and ambient declare const globals all qualify; an imported or locally declared binding does not), which here would be: the identifier's symbol has no declaration in the current source file.

Impact: 25 of the 64 one-sided prefer-optional-chain findings on one app (all typeof window|document|navigator|performance guards). Happy to send a PR with the fixture above as valid cases.

Disclosure: prepared with an AI assistant (agent session driven by me); both linters were run on the file above.

Activity

  1. added a commit that references this issue on Nov 29, 2026
    c52fd03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions