! claims that an optional chain, which may give undefined, is set

tx0/ts:bang-after-optional-chainrecommendedwarningbug

What it finds

const name = user?.name!, config?.get("a")!: ?. says that the value before it may be missing, and ! right after says that the result is certainly there. Both cannot be true. If the ?. stops early, the result is undefined, and what follows the ! throws or works with undefined while the type says it cannot.

Reported are non-null assertions that end an optional chain. Inside a chain, as in user?.profile!.name, TypeScript applies the ! only when the chain goes on, which is a sound claim, and that form is left alone. Some code writes x?.flags! & mask on purpose, relying on undefined & mask being 0, which is why the rule is recommended rather than on by default.

From the rule's source, bang_after_optional_chain.rs.

Example from the rule's tests
function read(user: { name?: string; profile?: { city: string } } | undefined) {  const name = user?.name!;tx0 reports: this ! contradicts the ?. before it  const city = user?.profile!.city;  const plain = user!.name;  return [name, city, plain];}
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 recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/ts:bang-after-optional-chain" = "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:bang-after-optional-chain] reason="..."

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