@typescript-eslint/no-non-null-asserted-nullish-coalescing
Disallow ! on the left side of ??
has suggestions
Also called typescript-eslint/no-non-null-asserted-nullish-coalescing, typescript/no-non-null-asserted-nullish-coalescing
?? gives a fallback for when the left side is null or undefined. A ! on that side says it never is. If that's true, the fallback is dead code. If it isn't, the ! is wrong. ?? handles both cases without it, so remove the !.
A ! on the right side is allowed.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"@typescript-eslint/no-non-null-asserted-nullish-coalescing" = "error"Examples#
example.ts2 problems
declare const settings: { theme?: string };
declare function findUser(id: string): { name: string } | null;
const theme = settings.theme!The nullish coalescing operator is designed to handle undefined and null - using a non-null assertion is not needed. ?? "light";
const user = findUser("42")!The nullish coalescing operator is designed to handle undefined and null - using a non-null assertion is not needed. ?? { name: "guest" };example.tsNo problems
declare const settings: { theme?: string };
declare function findUser(id: string): { name: string } | null;
const theme = settings.theme ?? "light";
const user = findUser("42") ?? { name: "guest" };Here the ! is what lets you read label before it's assigned, so it's allowed:
example.tsNo problems
let label: string;
const text = label! ?? "untitled";