Skip to content

feat: port rule @typescript-eslint/prefer-optional-chain#458

Open
fansenze wants to merge 1 commit intomainfrom
feat/port-rule-prefer_optional_chain-20260204
Open

feat: port rule @typescript-eslint/prefer-optional-chain#458
fansenze wants to merge 1 commit intomainfrom
feat/port-rule-prefer_optional_chain-20260204

Conversation

@fansenze
Copy link
Contributor

@fansenze fansenze commented Feb 5, 2026

Summary

Port the @typescript-eslint/prefer-optional-chain rule from TypeScript-ESLint to Go.

This rule enforces using concise optional chain expressions (?.) instead of chained logical ANDs (&&), negated logical ORs (||), or empty object coalescing patterns ((foo || {}).bar).

Implementation highlights

  • Operand gathering & classification: Flattens &&/|| chains into operands, classifying each as boolean, strict/loose null/undefined equality, typeof, or negation
  • Node comparison: Detects subset/prefix relationships between AST nodes to identify valid optional chain candidates, including support for type parameters (foo<string>()), type references (foo<T>()), and qualified names
  • DeMorgan inversion: For || chains, correctly inverts comparison operators during classification and restores original operators for output generation
  • Fix vs suggestion: Type-aware decision — auto-fix when the transformation preserves the expression's return type, suggestion otherwise
  • Chain building: Generates correct optional chain output with ?. placement, preserving type arguments, call arguments, element access, and comments
  • Options support: All 8 options from the original rule (checkAny, checkUnknown, checkString, checkNumber, checkBoolean, checkBigInt, requireNullish, allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing)

Related Links

Checklist

  • Tests updated (or not required).
  • Documentation updated (or not required).

@gemini-code-assist
Copy link

Summary of Changes

Hello @fansenze, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new linting rule, @typescript-eslint/prefer-optional-chain, to encourage more concise and readable code by transforming lengthy logical expressions into optional chaining. The rule analyzes complex logical structures involving nullish checks and property accesses, offering automated fixes or suggestions to simplify them into the modern optional chaining syntax. This enhancement improves code clarity and maintainability for TypeScript projects.

Highlights

  • Rule Porting: The @typescript-eslint/prefer-optional-chain rule has been ported from TypeScript-ESLint to Go, enforcing the use of optional chaining (?.) over verbose logical ANDs (&&), negated logical ORs (||), or empty object coalescing patterns ((foo || {}).bar).
  • Operand Analysis: The implementation includes sophisticated operand gathering and classification, flattening &&/|| chains and categorizing each operand by its type (boolean, null/undefined equality, typeof, negation).
  • Node Comparison and Chain Building: The rule intelligently detects subset/prefix relationships between AST nodes to identify valid optional chain candidates, supporting type parameters, type references, and qualified names. It also correctly generates optional chain output, preserving type arguments, call arguments, element access, and comments.
  • DeMorgan Inversion: For || chains, the rule correctly inverts comparison operators during classification and restores original operators for output generation, ensuring semantic correctness.
  • Fix vs. Suggestion Logic: The rule makes a type-aware decision to auto-fix when the transformation preserves the expression's return type, otherwise providing a suggestion to avoid unintended side effects.
  • Comprehensive Options Support: All eight options from the original rule are supported, including checkAny, checkUnknown, checkString, checkNumber, checkBoolean, checkBigInt, requireNullish, and allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing.
Changelog
  • go.work.sum
    • Updated hashes for golang.org/x/crypto to v0.47.0.
    • Added hash for golang.org/x/mod v0.31.0.
    • Updated hashes for golang.org/x/net to v0.49.0.
    • Added hash for golang.org/x/sys v0.30.0.
    • Updated hashes for golang.org/x/telemetry to v0.0.0-20260109210033-bd525da824e2.
    • Updated hashes for golang.org/x/tools to v0.40.0.
  • internal/config/config.go
    • Imported the new prefer_optional_chain rule.
    • Registered @typescript-eslint/prefer-optional-chain in the global rule registry.
  • internal/plugins/typescript/rules/prefer_optional_chain/analyze_chain.go
    • Added new file containing the ChainAnalyzer struct and its methods for analyzing logical chains, reporting issues, and building optional chain fix code.
    • Includes logic for determining fix safety (shouldUseFix), handling requireNullish option, and checking for vacuous strict guards.
  • internal/plugins/typescript/rules/prefer_optional_chain/base_cases_test.go
    • Added new file providing base case structures and helper functions (rawBaseCases, generateInvalidBaseCases, generateValidBaseCases) for generating comprehensive test scenarios for the prefer-optional-chain rule.
  • internal/plugins/typescript/rules/prefer_optional_chain/compare_nodes.go
    • Added new file defining NodeComparisonResult and compareNodesUncached function for deep comparison of AST nodes, crucial for identifying subset and equality relationships in chained expressions.
    • Includes isChainPrefix and isParenthesizedOptionalChain helpers for accurate node comparison.
  • internal/plugins/typescript/rules/prefer_optional_chain/gather_logical_operands.go
    • Added new file implementing OperandAnalyzer to gather and classify operands within logical expressions.
    • Defines OperandValidity, NullishComparisonType, and Operand structs to categorize different types of nullish checks and truthiness conditions.
  • internal/plugins/typescript/rules/prefer_optional_chain/prefer_optional_chain.go
    • Added new file defining the PreferOptionalChainRule and its options.
    • Sets up rule listeners for BinaryExpression, PropertyAccessExpression, and ElementAccessExpression to detect and process patterns suitable for optional chaining.
  • internal/plugins/typescript/rules/prefer_optional_chain/prefer_optional_chain.md
    • Added new documentation file detailing the prefer-optional-chain rule, including examples of incorrect and correct code, and explanations for all supported options.
  • internal/plugins/typescript/rules/prefer_optional_chain/prefer_optional_chain_test.go
    • Added new file containing extensive test cases for the prefer-optional-chain rule, combining generated base cases and hand-written edge cases to ensure robust coverage.
  • packages/rslint-test-tools/rstest.config.mts
    • Added the new test file prefer-optional-chain/prefer-optional-chain.test.ts to the test configuration.
  • packages/rslint-test-tools/tests/typescript-eslint/rules/prefer-optional-chain/prefer-optional-chain.test.ts
    • Updated existing TypeScript test cases to include new scenarios for type parameter chains and complex !== undefined checks, aligning with the Go implementation's test structures.
Activity
  • Tests have been updated to cover the new rule's functionality and various edge cases.
  • Documentation for the new rule has been added, explaining its purpose, usage, and configuration options.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This is an impressive and comprehensive port of the @typescript-eslint/prefer-optional-chain rule. The implementation covers a wide range of complex scenarios, including different logical operators, comparison types, type-aware checks, and even DeMorgan's law for || chains. The test suite is extensive and provides great confidence in the rule's correctness. I've found a few areas for potential improvement regarding code clarity and a couple of possible bugs, which I've detailed in the specific comments. Overall, this is a high-quality contribution.

@fansenze fansenze force-pushed the feat/port-rule-prefer_optional_chain-20260204 branch from 7a74ba6 to fbef01d Compare February 5, 2026 07:39
@fansenze fansenze requested a review from hardfist February 5, 2026 07:45
Port the prefer-optional-chain rule from TypeScript-ESLint to Go.

Key implementation details:
- Gather and classify logical operands from && and || chains
- Compare AST nodes to detect subset/prefix relationships for chain building
- Generate optional chain expressions with correct ?. placement
- Handle DeMorgan inversion for || chains (restore original operators for output)
- Type-aware fix vs suggestion decision based on expression return types
- Support type parameters in call expressions (e.g., foo?.<string>()?.bar)
- Handle all comparison types: boolean, loose/strict null/undefined equality

Includes comprehensive Go unit tests and TypeScript integration tests covering
base cases, hand-crafted edge cases, and generated permutations.
@fansenze fansenze force-pushed the feat/port-rule-prefer_optional_chain-20260204 branch from fbef01d to 911891c Compare February 9, 2026 06:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant