A ?. chain ends where undefined throws a TypeError

tx0/ts:unsafe-optional-chainingdefaultwarningbug

What it finds

(user?.getName)(), [...list?.items], const { id } = data?.user: an optional chain gives undefined when it stops early, and these places throw a TypeError on undefined. The ?. promises safety that the code around it takes away.

The places are: the callee or object of a call, member access, new or tagged template when the chain is in parentheses (without them, the chain would continue and stop safely); a spread in an array or arguments; the value destructured by a variable declaration; the iterated value of for-of; the right side of in and instanceof; and the base class of extends.

From the rule's source, unsafe_optional_chaining.rs.

Example from the rule's tests
function use(user: any, data: any, list: any) {  (user?.getName)();tx0 reports: user?.getName may be undefined, which throws when called  const all = [...list?.items];tx0 reports: which throws when spread  const { id } = data?.user;tx0 reports: which throws when destructured  for (const x of list?.items) {tx0 reports: which throws when iterated    all.push(x);  }  if ("id" in data?.user) {tx0 reports: which throws on the right of in    return id;  }  user?.getName();  const name = user?.profile.name;  return (data?.user)?.name ?? name;}
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 in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/ts:unsafe-optional-chaining" = "off"

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:unsafe-optional-chaining] reason="..."

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