a && a.b tests an object before reading from it where ?. would

tx0/ts:optional-chain-candidatestrictwarningstyle

What it finds

user && user.name tests an object and then reads a property of it, which user?.name writes once. The two differ only in what they give for a falsy user that is not null or undefined, such as 0 or "", where && gives that value and ?. reads the property.

Reported are a && a.b, a && a[b] and a && a.b() where the right operand starts with exactly the left one and the left one has no effects. Because of the difference for falsy values there is no fix, and this is a strict rule.

From the rule's source, optional_chain_candidate.rs.

Example from the rule's tests
export function name(user?: { profile?: { name: string } }) {  const a = user && user.profile;tx0 reports: ?. says the same  const b = user && user.profile && user.profile.name;tx0 reports: ?. says the same  const c = user && other.profile;  return [a, b, c];}declare const other: { profile: string };
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/ts:optional-chain-candidate" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/ts:optional-chain-candidate] reason="..."

tx0 explain tx0/ts:optional-chain-candidate shows the same in the terminal. Found a false positive? Report it.