Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

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

Disallow ! after an 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

Reported:

declare const user: { name: string; address?: { city: string } } | undefined;

const name: string = user?.name!;
const city: string = (user?.address?.city)!;

Not reported:

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:

declare const user: { name: string; address?: { city: string } } | undefined;

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