Skip to content

Latest commit

 

History

History
94 lines (66 loc) · 2.46 KB

File metadata and controls

94 lines (66 loc) · 2.46 KB

Expected Behavior: prefer-optional-chain Rule

This rule enforces the use of optional chaining (?.) over logical AND (&&) for property access when the same object is being checked and accessed.

Examples

Basic Property Access

- const name = user && user.name
+ const name = user?.name

- const email = user && user.profile && user.profile.email
+ const email = user?.profile?.email

- const count = data && data.items && data.items.length
+ const count = data?.items?.length

Method Calls

- const result = api && api.getData()
+ const result = api?.getData()

- const user = service && service.getUser(id)
+ const user = service?.getUser(id)

- const processed = data && data.filter().map()
+ const processed = data?.filter()?.map()

Computed Property Access

- const value = obj && obj[key]
+ const value = obj?.[key]

- const item = array && array[index]
+ const item = array?.[index]

- const prop = config && config[setting]
+ const prop = config?.[setting]

Function Returns

  function getUserName(user) {
-   return user && user.name
+   return user?.name
  }

- const getUserEmail = user => user && user.profile && user.profile.email
+ const getUserEmail = user => user?.profile?.email

Template Literals

- const greeting = `Hello ${user && user.name}!`
+ const greeting = `Hello ${user?.name}!`

- const status = `Count: ${data && data.items && data.items.length}`
+ const status = `Count: ${data?.items?.length}`

Rule Scope

This rule only applies to:

  • ✅ Logical AND (&&) operators where the same object is being checked and accessed:
    • object && object.propertyobject?.property
    • object && object.method()object?.method()
    • object && object[key]object?.[key]

This rule does NOT apply to:

  • ❌ Logical AND (&&) with different objects (user && profile.name)
  • ❌ Logical AND (&&) with literals (user && 'active')
  • ❌ Logical AND (&&) with function calls (user && getName())
  • ❌ Logical OR (||) operators
  • ❌ Already using optional chaining (user?.name)
  • ❌ Other logical operators (!, ??)

Auto-fix Behavior

The rule provides auto-fix suggestions that replace && with ?.:

  • user && user.nameuser?.name
  • user && user.getName()user?.getName()
  • obj && obj[key]obj?.[key]
  • api && api.getData(id)api?.getData(id)
  • user && user.profile && user.profile.emailuser?.profile?.email