@typescript-eslint/no-non-null-asserted-optional-chain

Disallow ! after an optional chain

warn by defaulthas suggestions

Also called typescript-eslint/no-non-null-asserted-optional-chain, typescript/no-non-null-asserted-optional-chain

user?.name is undefined when user is missing. That's what ?. is for. A ! after it tells TypeScript the result is never undefined, so the type no longer matches what happens at runtime, and the next line that uses the value can throw.

If user is always there, you don't need ?.. If it isn't, handle the undefined.

This rule is on by default in TypeScript files.

Configure#

On by default as a warning. To turn it off:

bunfig.toml
[lint.rules]
"@typescript-eslint/no-non-null-asserted-optional-chain" = "off" # or "error"

Examples#

example.ts2 problems
declare const user: { name: string; address?: { city: string } } | undefined;

const name: string = user?.name!;
const city: string = (user?.address?.city)!;
example.tsNo problems
declare const user: { name: string; address?: { city: string } } | undefined;

const name: string = user?.name ?? "guest";
const city: string | undefined = user?.address?.city;

A ! in the middle of the chain is allowed. Here it only applies to address, and only when there's a user:

example.tsNo problems
declare const user: { name: string; address?: { city: string } } | undefined;

const city: string | undefined = user?.address!.city;